project.rs

   1pub mod fs;
   2mod ignore;
   3pub mod worktree;
   4
   5use anyhow::{anyhow, Result};
   6use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
   7use clock::ReplicaId;
   8use collections::{hash_map, HashMap, HashSet};
   9use futures::Future;
  10use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
  11use gpui::{
  12    AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext, Task,
  13    WeakModelHandle,
  14};
  15use language::{
  16    proto::{deserialize_anchor, serialize_anchor},
  17    range_from_lsp, Bias, Buffer, Diagnostic, DiagnosticEntry, File as _, Language,
  18    LanguageRegistry, PointUtf16, ToOffset, ToPointUtf16,
  19};
  20use lsp::{DiagnosticSeverity, LanguageServer};
  21use postage::{prelude::Stream, watch};
  22use smol::block_on;
  23use std::{
  24    convert::TryInto,
  25    ops::Range,
  26    path::{Path, PathBuf},
  27    sync::{atomic::AtomicBool, Arc},
  28};
  29use util::{post_inc, ResultExt, TryFutureExt as _};
  30
  31pub use fs::*;
  32pub use worktree::*;
  33
  34pub struct Project {
  35    worktrees: Vec<WorktreeHandle>,
  36    active_entry: Option<ProjectEntry>,
  37    languages: Arc<LanguageRegistry>,
  38    language_servers: HashMap<(WorktreeId, String), Arc<LanguageServer>>,
  39    client: Arc<client::Client>,
  40    user_store: ModelHandle<UserStore>,
  41    fs: Arc<dyn Fs>,
  42    client_state: ProjectClientState,
  43    collaborators: HashMap<PeerId, Collaborator>,
  44    subscriptions: Vec<client::Subscription>,
  45    language_servers_with_diagnostics_running: isize,
  46    open_buffers: HashMap<usize, WeakModelHandle<Buffer>>,
  47    loading_buffers: HashMap<
  48        ProjectPath,
  49        postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
  50    >,
  51    shared_buffers: HashMap<PeerId, HashMap<u64, ModelHandle<Buffer>>>,
  52}
  53
  54enum WorktreeHandle {
  55    Strong(ModelHandle<Worktree>),
  56    Weak(WeakModelHandle<Worktree>),
  57}
  58
  59enum ProjectClientState {
  60    Local {
  61        is_shared: bool,
  62        remote_id_tx: watch::Sender<Option<u64>>,
  63        remote_id_rx: watch::Receiver<Option<u64>>,
  64        _maintain_remote_id_task: Task<Option<()>>,
  65    },
  66    Remote {
  67        sharing_has_stopped: bool,
  68        remote_id: u64,
  69        replica_id: ReplicaId,
  70    },
  71}
  72
  73#[derive(Clone, Debug)]
  74pub struct Collaborator {
  75    pub user: Arc<User>,
  76    pub peer_id: PeerId,
  77    pub replica_id: ReplicaId,
  78}
  79
  80#[derive(Clone, Debug, PartialEq)]
  81pub enum Event {
  82    ActiveEntryChanged(Option<ProjectEntry>),
  83    WorktreeRemoved(WorktreeId),
  84    DiskBasedDiagnosticsStarted,
  85    DiskBasedDiagnosticsUpdated,
  86    DiskBasedDiagnosticsFinished,
  87    DiagnosticsUpdated(ProjectPath),
  88}
  89
  90#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
  91pub struct ProjectPath {
  92    pub worktree_id: WorktreeId,
  93    pub path: Arc<Path>,
  94}
  95
  96#[derive(Clone, Debug, Default, PartialEq)]
  97pub struct DiagnosticSummary {
  98    pub error_count: usize,
  99    pub warning_count: usize,
 100    pub info_count: usize,
 101    pub hint_count: usize,
 102}
 103
 104#[derive(Debug)]
 105pub struct Definition {
 106    pub target_buffer: ModelHandle<Buffer>,
 107    pub target_range: Range<language::Anchor>,
 108}
 109
 110impl DiagnosticSummary {
 111    fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
 112        let mut this = Self {
 113            error_count: 0,
 114            warning_count: 0,
 115            info_count: 0,
 116            hint_count: 0,
 117        };
 118
 119        for entry in diagnostics {
 120            if entry.diagnostic.is_primary {
 121                match entry.diagnostic.severity {
 122                    DiagnosticSeverity::ERROR => this.error_count += 1,
 123                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 124                    DiagnosticSeverity::INFORMATION => this.info_count += 1,
 125                    DiagnosticSeverity::HINT => this.hint_count += 1,
 126                    _ => {}
 127                }
 128            }
 129        }
 130
 131        this
 132    }
 133
 134    pub fn to_proto(&self, path: Arc<Path>) -> proto::DiagnosticSummary {
 135        proto::DiagnosticSummary {
 136            path: path.to_string_lossy().to_string(),
 137            error_count: self.error_count as u32,
 138            warning_count: self.warning_count as u32,
 139            info_count: self.info_count as u32,
 140            hint_count: self.hint_count as u32,
 141        }
 142    }
 143}
 144
 145#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 146pub struct ProjectEntry {
 147    pub worktree_id: WorktreeId,
 148    pub entry_id: usize,
 149}
 150
 151impl Project {
 152    pub fn local(
 153        client: Arc<Client>,
 154        user_store: ModelHandle<UserStore>,
 155        languages: Arc<LanguageRegistry>,
 156        fs: Arc<dyn Fs>,
 157        cx: &mut MutableAppContext,
 158    ) -> ModelHandle<Self> {
 159        cx.add_model(|cx: &mut ModelContext<Self>| {
 160            let (remote_id_tx, remote_id_rx) = watch::channel();
 161            let _maintain_remote_id_task = cx.spawn_weak({
 162                let rpc = client.clone();
 163                move |this, mut cx| {
 164                    async move {
 165                        let mut status = rpc.status();
 166                        while let Some(status) = status.recv().await {
 167                            if let Some(this) = this.upgrade(&cx) {
 168                                let remote_id = if let client::Status::Connected { .. } = status {
 169                                    let response = rpc.request(proto::RegisterProject {}).await?;
 170                                    Some(response.project_id)
 171                                } else {
 172                                    None
 173                                };
 174
 175                                if let Some(project_id) = remote_id {
 176                                    let mut registrations = Vec::new();
 177                                    this.update(&mut cx, |this, cx| {
 178                                        for worktree in this.worktrees(cx).collect::<Vec<_>>() {
 179                                            registrations.push(worktree.update(
 180                                                cx,
 181                                                |worktree, cx| {
 182                                                    let worktree = worktree.as_local_mut().unwrap();
 183                                                    worktree.register(project_id, cx)
 184                                                },
 185                                            ));
 186                                        }
 187                                    });
 188                                    for registration in registrations {
 189                                        registration.await?;
 190                                    }
 191                                }
 192                                this.update(&mut cx, |this, cx| this.set_remote_id(remote_id, cx));
 193                            }
 194                        }
 195                        Ok(())
 196                    }
 197                    .log_err()
 198                }
 199            });
 200
 201            Self {
 202                worktrees: Default::default(),
 203                collaborators: Default::default(),
 204                open_buffers: Default::default(),
 205                loading_buffers: Default::default(),
 206                shared_buffers: Default::default(),
 207                client_state: ProjectClientState::Local {
 208                    is_shared: false,
 209                    remote_id_tx,
 210                    remote_id_rx,
 211                    _maintain_remote_id_task,
 212                },
 213                subscriptions: Vec::new(),
 214                active_entry: None,
 215                languages,
 216                client,
 217                user_store,
 218                fs,
 219                language_servers_with_diagnostics_running: 0,
 220                language_servers: Default::default(),
 221            }
 222        })
 223    }
 224
 225    pub async fn remote(
 226        remote_id: u64,
 227        client: Arc<Client>,
 228        user_store: ModelHandle<UserStore>,
 229        languages: Arc<LanguageRegistry>,
 230        fs: Arc<dyn Fs>,
 231        cx: &mut AsyncAppContext,
 232    ) -> Result<ModelHandle<Self>> {
 233        client.authenticate_and_connect(&cx).await?;
 234
 235        let response = client
 236            .request(proto::JoinProject {
 237                project_id: remote_id,
 238            })
 239            .await?;
 240
 241        let replica_id = response.replica_id as ReplicaId;
 242
 243        let mut worktrees = Vec::new();
 244        for worktree in response.worktrees {
 245            let (worktree, load_task) = cx
 246                .update(|cx| Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx));
 247            worktrees.push(worktree);
 248            load_task.detach();
 249        }
 250
 251        let user_ids = response
 252            .collaborators
 253            .iter()
 254            .map(|peer| peer.user_id)
 255            .collect();
 256        user_store
 257            .update(cx, |user_store, cx| user_store.load_users(user_ids, cx))
 258            .await?;
 259        let mut collaborators = HashMap::default();
 260        for message in response.collaborators {
 261            let collaborator = Collaborator::from_proto(message, &user_store, cx).await?;
 262            collaborators.insert(collaborator.peer_id, collaborator);
 263        }
 264
 265        Ok(cx.add_model(|cx| {
 266            let mut this = Self {
 267                worktrees: Vec::new(),
 268                open_buffers: Default::default(),
 269                loading_buffers: Default::default(),
 270                shared_buffers: Default::default(),
 271                active_entry: None,
 272                collaborators,
 273                languages,
 274                user_store,
 275                fs,
 276                subscriptions: vec![
 277                    client.subscribe_to_entity(remote_id, cx, Self::handle_unshare_project),
 278                    client.subscribe_to_entity(remote_id, cx, Self::handle_add_collaborator),
 279                    client.subscribe_to_entity(remote_id, cx, Self::handle_remove_collaborator),
 280                    client.subscribe_to_entity(remote_id, cx, Self::handle_share_worktree),
 281                    client.subscribe_to_entity(remote_id, cx, Self::handle_unregister_worktree),
 282                    client.subscribe_to_entity(remote_id, cx, Self::handle_update_worktree),
 283                    client.subscribe_to_entity(
 284                        remote_id,
 285                        cx,
 286                        Self::handle_update_diagnostic_summary,
 287                    ),
 288                    client.subscribe_to_entity(
 289                        remote_id,
 290                        cx,
 291                        Self::handle_disk_based_diagnostics_updating,
 292                    ),
 293                    client.subscribe_to_entity(
 294                        remote_id,
 295                        cx,
 296                        Self::handle_disk_based_diagnostics_updated,
 297                    ),
 298                    client.subscribe_to_entity(remote_id, cx, Self::handle_update_buffer),
 299                    client.subscribe_to_entity(remote_id, cx, Self::handle_update_buffer_file),
 300                    client.subscribe_to_entity(remote_id, cx, Self::handle_buffer_reloaded),
 301                    client.subscribe_to_entity(remote_id, cx, Self::handle_buffer_saved),
 302                ],
 303                client,
 304                client_state: ProjectClientState::Remote {
 305                    sharing_has_stopped: false,
 306                    remote_id,
 307                    replica_id,
 308                },
 309                language_servers_with_diagnostics_running: 0,
 310                language_servers: Default::default(),
 311            };
 312            for worktree in worktrees {
 313                this.add_worktree(&worktree, cx);
 314            }
 315            this
 316        }))
 317    }
 318
 319    fn set_remote_id(&mut self, remote_id: Option<u64>, cx: &mut ModelContext<Self>) {
 320        if let ProjectClientState::Local { remote_id_tx, .. } = &mut self.client_state {
 321            *remote_id_tx.borrow_mut() = remote_id;
 322        }
 323
 324        self.subscriptions.clear();
 325        if let Some(remote_id) = remote_id {
 326            let client = &self.client;
 327            self.subscriptions.extend([
 328                client.subscribe_to_entity(remote_id, cx, Self::handle_open_buffer),
 329                client.subscribe_to_entity(remote_id, cx, Self::handle_close_buffer),
 330                client.subscribe_to_entity(remote_id, cx, Self::handle_add_collaborator),
 331                client.subscribe_to_entity(remote_id, cx, Self::handle_remove_collaborator),
 332                client.subscribe_to_entity(remote_id, cx, Self::handle_update_worktree),
 333                client.subscribe_to_entity(remote_id, cx, Self::handle_update_buffer),
 334                client.subscribe_to_entity(remote_id, cx, Self::handle_save_buffer),
 335                client.subscribe_to_entity(remote_id, cx, Self::handle_buffer_saved),
 336                client.subscribe_to_entity(remote_id, cx, Self::handle_format_buffer),
 337                client.subscribe_to_entity(remote_id, cx, Self::handle_get_completions),
 338                client.subscribe_to_entity(
 339                    remote_id,
 340                    cx,
 341                    Self::handle_apply_additional_edits_for_completion,
 342                ),
 343                client.subscribe_to_entity(remote_id, cx, Self::handle_get_definition),
 344            ]);
 345        }
 346    }
 347
 348    pub fn remote_id(&self) -> Option<u64> {
 349        match &self.client_state {
 350            ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
 351            ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
 352        }
 353    }
 354
 355    pub fn next_remote_id(&self) -> impl Future<Output = u64> {
 356        let mut id = None;
 357        let mut watch = None;
 358        match &self.client_state {
 359            ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
 360            ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
 361        }
 362
 363        async move {
 364            if let Some(id) = id {
 365                return id;
 366            }
 367            let mut watch = watch.unwrap();
 368            loop {
 369                let id = *watch.borrow();
 370                if let Some(id) = id {
 371                    return id;
 372                }
 373                watch.recv().await;
 374            }
 375        }
 376    }
 377
 378    pub fn replica_id(&self) -> ReplicaId {
 379        match &self.client_state {
 380            ProjectClientState::Local { .. } => 0,
 381            ProjectClientState::Remote { replica_id, .. } => *replica_id,
 382        }
 383    }
 384
 385    pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
 386        &self.collaborators
 387    }
 388
 389    pub fn worktrees<'a>(
 390        &'a self,
 391        cx: &'a AppContext,
 392    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 393        self.worktrees
 394            .iter()
 395            .filter_map(move |worktree| worktree.upgrade(cx))
 396    }
 397
 398    pub fn worktree_for_id(
 399        &self,
 400        id: WorktreeId,
 401        cx: &AppContext,
 402    ) -> Option<ModelHandle<Worktree>> {
 403        self.worktrees(cx)
 404            .find(|worktree| worktree.read(cx).id() == id)
 405    }
 406
 407    pub fn share(&self, cx: &mut ModelContext<Self>) -> Task<anyhow::Result<()>> {
 408        let rpc = self.client.clone();
 409        cx.spawn(|this, mut cx| async move {
 410            let project_id = this.update(&mut cx, |this, _| {
 411                if let ProjectClientState::Local {
 412                    is_shared,
 413                    remote_id_rx,
 414                    ..
 415                } = &mut this.client_state
 416                {
 417                    *is_shared = true;
 418                    remote_id_rx
 419                        .borrow()
 420                        .ok_or_else(|| anyhow!("no project id"))
 421                } else {
 422                    Err(anyhow!("can't share a remote project"))
 423                }
 424            })?;
 425
 426            rpc.request(proto::ShareProject { project_id }).await?;
 427            let mut tasks = Vec::new();
 428            this.update(&mut cx, |this, cx| {
 429                for worktree in this.worktrees(cx).collect::<Vec<_>>() {
 430                    worktree.update(cx, |worktree, cx| {
 431                        let worktree = worktree.as_local_mut().unwrap();
 432                        tasks.push(worktree.share(project_id, cx));
 433                    });
 434                }
 435            });
 436            for task in tasks {
 437                task.await?;
 438            }
 439            this.update(&mut cx, |_, cx| cx.notify());
 440            Ok(())
 441        })
 442    }
 443
 444    pub fn unshare(&self, cx: &mut ModelContext<Self>) -> Task<anyhow::Result<()>> {
 445        let rpc = self.client.clone();
 446        cx.spawn(|this, mut cx| async move {
 447            let project_id = this.update(&mut cx, |this, _| {
 448                if let ProjectClientState::Local {
 449                    is_shared,
 450                    remote_id_rx,
 451                    ..
 452                } = &mut this.client_state
 453                {
 454                    *is_shared = false;
 455                    remote_id_rx
 456                        .borrow()
 457                        .ok_or_else(|| anyhow!("no project id"))
 458                } else {
 459                    Err(anyhow!("can't share a remote project"))
 460                }
 461            })?;
 462
 463            rpc.send(proto::UnshareProject { project_id }).await?;
 464            this.update(&mut cx, |this, cx| {
 465                this.collaborators.clear();
 466                this.shared_buffers.clear();
 467                for worktree in this.worktrees(cx).collect::<Vec<_>>() {
 468                    worktree.update(cx, |worktree, _| {
 469                        worktree.as_local_mut().unwrap().unshare();
 470                    });
 471                }
 472                cx.notify()
 473            });
 474            Ok(())
 475        })
 476    }
 477
 478    pub fn is_read_only(&self) -> bool {
 479        match &self.client_state {
 480            ProjectClientState::Local { .. } => false,
 481            ProjectClientState::Remote {
 482                sharing_has_stopped,
 483                ..
 484            } => *sharing_has_stopped,
 485        }
 486    }
 487
 488    pub fn is_local(&self) -> bool {
 489        match &self.client_state {
 490            ProjectClientState::Local { .. } => true,
 491            ProjectClientState::Remote { .. } => false,
 492        }
 493    }
 494
 495    pub fn open_buffer(
 496        &mut self,
 497        path: impl Into<ProjectPath>,
 498        cx: &mut ModelContext<Self>,
 499    ) -> Task<Result<ModelHandle<Buffer>>> {
 500        let project_path = path.into();
 501        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
 502            worktree
 503        } else {
 504            return Task::ready(Err(anyhow!("no such worktree")));
 505        };
 506
 507        // If there is already a buffer for the given path, then return it.
 508        let existing_buffer = self.get_open_buffer(&project_path, cx);
 509        if let Some(existing_buffer) = existing_buffer {
 510            return Task::ready(Ok(existing_buffer));
 511        }
 512
 513        let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
 514            // If the given path is already being loaded, then wait for that existing
 515            // task to complete and return the same buffer.
 516            hash_map::Entry::Occupied(e) => e.get().clone(),
 517
 518            // Otherwise, record the fact that this path is now being loaded.
 519            hash_map::Entry::Vacant(entry) => {
 520                let (mut tx, rx) = postage::watch::channel();
 521                entry.insert(rx.clone());
 522
 523                let load_buffer = if worktree.read(cx).is_local() {
 524                    self.open_local_buffer(&project_path.path, &worktree, cx)
 525                } else {
 526                    self.open_remote_buffer(&project_path.path, &worktree, cx)
 527                };
 528
 529                cx.spawn(move |this, mut cx| async move {
 530                    let load_result = load_buffer.await;
 531                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
 532                        // Record the fact that the buffer is no longer loading.
 533                        this.loading_buffers.remove(&project_path);
 534                        let buffer = load_result.map_err(Arc::new)?;
 535                        Ok(buffer)
 536                    }));
 537                })
 538                .detach();
 539                rx
 540            }
 541        };
 542
 543        cx.foreground().spawn(async move {
 544            loop {
 545                if let Some(result) = loading_watch.borrow().as_ref() {
 546                    match result {
 547                        Ok(buffer) => return Ok(buffer.clone()),
 548                        Err(error) => return Err(anyhow!("{}", error)),
 549                    }
 550                }
 551                loading_watch.recv().await;
 552            }
 553        })
 554    }
 555
 556    fn open_local_buffer(
 557        &mut self,
 558        path: &Arc<Path>,
 559        worktree: &ModelHandle<Worktree>,
 560        cx: &mut ModelContext<Self>,
 561    ) -> Task<Result<ModelHandle<Buffer>>> {
 562        let load_buffer = worktree.update(cx, |worktree, cx| {
 563            let worktree = worktree.as_local_mut().unwrap();
 564            worktree.load_buffer(path, cx)
 565        });
 566        let worktree = worktree.downgrade();
 567        cx.spawn(|this, mut cx| async move {
 568            let buffer = load_buffer.await?;
 569            let worktree = worktree
 570                .upgrade(&cx)
 571                .ok_or_else(|| anyhow!("worktree was removed"))?;
 572            this.update(&mut cx, |this, cx| {
 573                this.register_buffer(&buffer, Some(&worktree), cx)
 574            })?;
 575            Ok(buffer)
 576        })
 577    }
 578
 579    fn open_remote_buffer(
 580        &mut self,
 581        path: &Arc<Path>,
 582        worktree: &ModelHandle<Worktree>,
 583        cx: &mut ModelContext<Self>,
 584    ) -> Task<Result<ModelHandle<Buffer>>> {
 585        let rpc = self.client.clone();
 586        let project_id = self.remote_id().unwrap();
 587        let remote_worktree_id = worktree.read(cx).id();
 588        let path = path.clone();
 589        let path_string = path.to_string_lossy().to_string();
 590        cx.spawn(|this, mut cx| async move {
 591            let response = rpc
 592                .request(proto::OpenBuffer {
 593                    project_id,
 594                    worktree_id: remote_worktree_id.to_proto(),
 595                    path: path_string,
 596                })
 597                .await?;
 598            let buffer = response.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
 599            this.update(&mut cx, |this, cx| {
 600                this.deserialize_remote_buffer(buffer, cx)
 601            })
 602        })
 603    }
 604
 605    pub fn save_buffer_as(
 606        &self,
 607        buffer: ModelHandle<Buffer>,
 608        abs_path: PathBuf,
 609        cx: &mut ModelContext<Project>,
 610    ) -> Task<Result<()>> {
 611        let worktree_task = self.find_or_create_local_worktree(&abs_path, false, cx);
 612        cx.spawn(|this, mut cx| async move {
 613            let (worktree, path) = worktree_task.await?;
 614            worktree
 615                .update(&mut cx, |worktree, cx| {
 616                    worktree
 617                        .as_local_mut()
 618                        .unwrap()
 619                        .save_buffer_as(buffer.clone(), path, cx)
 620                })
 621                .await?;
 622            this.update(&mut cx, |this, cx| {
 623                this.assign_language_to_buffer(&buffer, Some(&worktree), cx);
 624            });
 625            Ok(())
 626        })
 627    }
 628
 629    #[cfg(any(test, feature = "test-support"))]
 630    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 631        let path = path.into();
 632        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 633            self.open_buffers.iter().any(|(_, buffer)| {
 634                if let Some(buffer) = buffer.upgrade(cx) {
 635                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 636                        if file.worktree == worktree && file.path() == &path.path {
 637                            return true;
 638                        }
 639                    }
 640                }
 641                false
 642            })
 643        } else {
 644            false
 645        }
 646    }
 647
 648    fn get_open_buffer(
 649        &mut self,
 650        path: &ProjectPath,
 651        cx: &mut ModelContext<Self>,
 652    ) -> Option<ModelHandle<Buffer>> {
 653        let mut result = None;
 654        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
 655        self.open_buffers.retain(|_, buffer| {
 656            if let Some(buffer) = buffer.upgrade(cx) {
 657                if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 658                    if file.worktree == worktree && file.path() == &path.path {
 659                        result = Some(buffer);
 660                    }
 661                }
 662                true
 663            } else {
 664                false
 665            }
 666        });
 667        result
 668    }
 669
 670    fn register_buffer(
 671        &mut self,
 672        buffer: &ModelHandle<Buffer>,
 673        worktree: Option<&ModelHandle<Worktree>>,
 674        cx: &mut ModelContext<Self>,
 675    ) -> Result<()> {
 676        if self
 677            .open_buffers
 678            .insert(buffer.read(cx).remote_id() as usize, buffer.downgrade())
 679            .is_some()
 680        {
 681            return Err(anyhow!("registered the same buffer twice"));
 682        }
 683        self.assign_language_to_buffer(&buffer, worktree, cx);
 684        Ok(())
 685    }
 686
 687    fn assign_language_to_buffer(
 688        &mut self,
 689        buffer: &ModelHandle<Buffer>,
 690        worktree: Option<&ModelHandle<Worktree>>,
 691        cx: &mut ModelContext<Self>,
 692    ) -> Option<()> {
 693        let (path, full_path) = {
 694            let file = buffer.read(cx).file()?;
 695            (file.path().clone(), file.full_path(cx))
 696        };
 697
 698        // If the buffer has a language, set it and start/assign the language server
 699        if let Some(language) = self.languages.select_language(&full_path) {
 700            buffer.update(cx, |buffer, cx| {
 701                buffer.set_language(Some(language.clone()), cx);
 702            });
 703
 704            // For local worktrees, start a language server if needed.
 705            // Also assign the language server and any previously stored diagnostics to the buffer.
 706            if let Some(local_worktree) = worktree.and_then(|w| w.read(cx).as_local()) {
 707                let worktree_id = local_worktree.id();
 708                let worktree_abs_path = local_worktree.abs_path().clone();
 709
 710                let language_server = match self
 711                    .language_servers
 712                    .entry((worktree_id, language.name().to_string()))
 713                {
 714                    hash_map::Entry::Occupied(e) => Some(e.get().clone()),
 715                    hash_map::Entry::Vacant(e) => Self::start_language_server(
 716                        self.client.clone(),
 717                        language.clone(),
 718                        &worktree_abs_path,
 719                        cx,
 720                    )
 721                    .map(|server| e.insert(server).clone()),
 722                };
 723
 724                buffer.update(cx, |buffer, cx| {
 725                    buffer.set_language_server(language_server, cx);
 726                });
 727            }
 728        }
 729
 730        if let Some(local_worktree) = worktree.and_then(|w| w.read(cx).as_local()) {
 731            if let Some(diagnostics) = local_worktree.diagnostics_for_path(&path) {
 732                buffer.update(cx, |buffer, cx| {
 733                    buffer.update_diagnostics(None, diagnostics, cx).log_err();
 734                });
 735            }
 736        }
 737
 738        None
 739    }
 740
 741    fn start_language_server(
 742        rpc: Arc<Client>,
 743        language: Arc<Language>,
 744        worktree_path: &Path,
 745        cx: &mut ModelContext<Self>,
 746    ) -> Option<Arc<LanguageServer>> {
 747        enum LspEvent {
 748            DiagnosticsStart,
 749            DiagnosticsUpdate(lsp::PublishDiagnosticsParams),
 750            DiagnosticsFinish,
 751        }
 752
 753        let language_server = language
 754            .start_server(worktree_path, cx)
 755            .log_err()
 756            .flatten()?;
 757        let disk_based_sources = language
 758            .disk_based_diagnostic_sources()
 759            .cloned()
 760            .unwrap_or_default();
 761        let disk_based_diagnostics_progress_token =
 762            language.disk_based_diagnostics_progress_token().cloned();
 763        let has_disk_based_diagnostic_progress_token =
 764            disk_based_diagnostics_progress_token.is_some();
 765        let (diagnostics_tx, diagnostics_rx) = smol::channel::unbounded();
 766
 767        // Listen for `PublishDiagnostics` notifications.
 768        language_server
 769            .on_notification::<lsp::notification::PublishDiagnostics, _>({
 770                let diagnostics_tx = diagnostics_tx.clone();
 771                move |params| {
 772                    if !has_disk_based_diagnostic_progress_token {
 773                        block_on(diagnostics_tx.send(LspEvent::DiagnosticsStart)).ok();
 774                    }
 775                    block_on(diagnostics_tx.send(LspEvent::DiagnosticsUpdate(params))).ok();
 776                    if !has_disk_based_diagnostic_progress_token {
 777                        block_on(diagnostics_tx.send(LspEvent::DiagnosticsFinish)).ok();
 778                    }
 779                }
 780            })
 781            .detach();
 782
 783        // Listen for `Progress` notifications. Send an event when the language server
 784        // transitions between running jobs and not running any jobs.
 785        let mut running_jobs_for_this_server: i32 = 0;
 786        language_server
 787            .on_notification::<lsp::notification::Progress, _>(move |params| {
 788                let token = match params.token {
 789                    lsp::NumberOrString::Number(_) => None,
 790                    lsp::NumberOrString::String(token) => Some(token),
 791                };
 792
 793                if token == disk_based_diagnostics_progress_token {
 794                    match params.value {
 795                        lsp::ProgressParamsValue::WorkDone(progress) => match progress {
 796                            lsp::WorkDoneProgress::Begin(_) => {
 797                                running_jobs_for_this_server += 1;
 798                                if running_jobs_for_this_server == 1 {
 799                                    block_on(diagnostics_tx.send(LspEvent::DiagnosticsStart)).ok();
 800                                }
 801                            }
 802                            lsp::WorkDoneProgress::End(_) => {
 803                                running_jobs_for_this_server -= 1;
 804                                if running_jobs_for_this_server == 0 {
 805                                    block_on(diagnostics_tx.send(LspEvent::DiagnosticsFinish)).ok();
 806                                }
 807                            }
 808                            _ => {}
 809                        },
 810                    }
 811                }
 812            })
 813            .detach();
 814
 815        // Process all the LSP events.
 816        cx.spawn_weak(|this, mut cx| async move {
 817            while let Ok(message) = diagnostics_rx.recv().await {
 818                let this = cx.read(|cx| this.upgrade(cx))?;
 819                match message {
 820                    LspEvent::DiagnosticsStart => {
 821                        let send = this.update(&mut cx, |this, cx| {
 822                            this.disk_based_diagnostics_started(cx);
 823                            this.remote_id().map(|project_id| {
 824                                rpc.send(proto::DiskBasedDiagnosticsUpdating { project_id })
 825                            })
 826                        });
 827                        if let Some(send) = send {
 828                            send.await.log_err();
 829                        }
 830                    }
 831                    LspEvent::DiagnosticsUpdate(mut params) => {
 832                        language.process_diagnostics(&mut params);
 833                        this.update(&mut cx, |this, cx| {
 834                            this.update_diagnostics(params, &disk_based_sources, cx)
 835                                .log_err();
 836                        });
 837                    }
 838                    LspEvent::DiagnosticsFinish => {
 839                        let send = this.update(&mut cx, |this, cx| {
 840                            this.disk_based_diagnostics_finished(cx);
 841                            this.remote_id().map(|project_id| {
 842                                rpc.send(proto::DiskBasedDiagnosticsUpdated { project_id })
 843                            })
 844                        });
 845                        if let Some(send) = send {
 846                            send.await.log_err();
 847                        }
 848                    }
 849                }
 850            }
 851            Some(())
 852        })
 853        .detach();
 854
 855        Some(language_server)
 856    }
 857
 858    pub fn update_diagnostics(
 859        &mut self,
 860        params: lsp::PublishDiagnosticsParams,
 861        disk_based_sources: &HashSet<String>,
 862        cx: &mut ModelContext<Self>,
 863    ) -> Result<()> {
 864        let abs_path = params
 865            .uri
 866            .to_file_path()
 867            .map_err(|_| anyhow!("URI is not a file"))?;
 868        let mut next_group_id = 0;
 869        let mut diagnostics = Vec::default();
 870        let mut primary_diagnostic_group_ids = HashMap::default();
 871        let mut sources_by_group_id = HashMap::default();
 872        let mut supporting_diagnostic_severities = HashMap::default();
 873        for diagnostic in &params.diagnostics {
 874            let source = diagnostic.source.as_ref();
 875            let code = diagnostic.code.as_ref().map(|code| match code {
 876                lsp::NumberOrString::Number(code) => code.to_string(),
 877                lsp::NumberOrString::String(code) => code.clone(),
 878            });
 879            let range = range_from_lsp(diagnostic.range);
 880            let is_supporting = diagnostic
 881                .related_information
 882                .as_ref()
 883                .map_or(false, |infos| {
 884                    infos.iter().any(|info| {
 885                        primary_diagnostic_group_ids.contains_key(&(
 886                            source,
 887                            code.clone(),
 888                            range_from_lsp(info.location.range),
 889                        ))
 890                    })
 891                });
 892
 893            if is_supporting {
 894                if let Some(severity) = diagnostic.severity {
 895                    supporting_diagnostic_severities
 896                        .insert((source, code.clone(), range), severity);
 897                }
 898            } else {
 899                let group_id = post_inc(&mut next_group_id);
 900                let is_disk_based =
 901                    source.map_or(false, |source| disk_based_sources.contains(source));
 902
 903                sources_by_group_id.insert(group_id, source);
 904                primary_diagnostic_group_ids
 905                    .insert((source, code.clone(), range.clone()), group_id);
 906
 907                diagnostics.push(DiagnosticEntry {
 908                    range,
 909                    diagnostic: Diagnostic {
 910                        code: code.clone(),
 911                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
 912                        message: diagnostic.message.clone(),
 913                        group_id,
 914                        is_primary: true,
 915                        is_valid: true,
 916                        is_disk_based,
 917                    },
 918                });
 919                if let Some(infos) = &diagnostic.related_information {
 920                    for info in infos {
 921                        if info.location.uri == params.uri && !info.message.is_empty() {
 922                            let range = range_from_lsp(info.location.range);
 923                            diagnostics.push(DiagnosticEntry {
 924                                range,
 925                                diagnostic: Diagnostic {
 926                                    code: code.clone(),
 927                                    severity: DiagnosticSeverity::INFORMATION,
 928                                    message: info.message.clone(),
 929                                    group_id,
 930                                    is_primary: false,
 931                                    is_valid: true,
 932                                    is_disk_based,
 933                                },
 934                            });
 935                        }
 936                    }
 937                }
 938            }
 939        }
 940
 941        for entry in &mut diagnostics {
 942            let diagnostic = &mut entry.diagnostic;
 943            if !diagnostic.is_primary {
 944                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
 945                if let Some(&severity) = supporting_diagnostic_severities.get(&(
 946                    source,
 947                    diagnostic.code.clone(),
 948                    entry.range.clone(),
 949                )) {
 950                    diagnostic.severity = severity;
 951                }
 952            }
 953        }
 954
 955        self.update_diagnostic_entries(abs_path, params.version, diagnostics, cx)?;
 956        Ok(())
 957    }
 958
 959    pub fn update_diagnostic_entries(
 960        &mut self,
 961        abs_path: PathBuf,
 962        version: Option<i32>,
 963        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
 964        cx: &mut ModelContext<Project>,
 965    ) -> Result<(), anyhow::Error> {
 966        let (worktree, relative_path) = self
 967            .find_local_worktree(&abs_path, cx)
 968            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
 969        let project_path = ProjectPath {
 970            worktree_id: worktree.read(cx).id(),
 971            path: relative_path.into(),
 972        };
 973
 974        for buffer in self.open_buffers.values() {
 975            if let Some(buffer) = buffer.upgrade(cx) {
 976                if buffer
 977                    .read(cx)
 978                    .file()
 979                    .map_or(false, |file| *file.path() == project_path.path)
 980                {
 981                    buffer.update(cx, |buffer, cx| {
 982                        buffer.update_diagnostics(version, diagnostics.clone(), cx)
 983                    })?;
 984                    break;
 985                }
 986            }
 987        }
 988        worktree.update(cx, |worktree, cx| {
 989            worktree
 990                .as_local_mut()
 991                .ok_or_else(|| anyhow!("not a local worktree"))?
 992                .update_diagnostics(project_path.path.clone(), diagnostics, cx)
 993        })?;
 994        cx.emit(Event::DiagnosticsUpdated(project_path));
 995        Ok(())
 996    }
 997
 998    pub fn definition<T: ToOffset>(
 999        &self,
1000        source_buffer_handle: &ModelHandle<Buffer>,
1001        position: T,
1002        cx: &mut ModelContext<Self>,
1003    ) -> Task<Result<Vec<Definition>>> {
1004        let source_buffer_handle = source_buffer_handle.clone();
1005        let source_buffer = source_buffer_handle.read(cx);
1006        let worktree;
1007        let buffer_abs_path;
1008        if let Some(file) = File::from_dyn(source_buffer.file()) {
1009            worktree = file.worktree.clone();
1010            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
1011        } else {
1012            return Task::ready(Err(anyhow!("buffer does not belong to any worktree")));
1013        };
1014
1015        if worktree.read(cx).as_local().is_some() {
1016            let point = source_buffer.offset_to_point_utf16(position.to_offset(source_buffer));
1017            let buffer_abs_path = buffer_abs_path.unwrap();
1018            let lang_name;
1019            let lang_server;
1020            if let Some(lang) = source_buffer.language() {
1021                lang_name = lang.name().to_string();
1022                if let Some(server) = self
1023                    .language_servers
1024                    .get(&(worktree.read(cx).id(), lang_name.clone()))
1025                {
1026                    lang_server = server.clone();
1027                } else {
1028                    return Task::ready(Err(anyhow!("buffer does not have a language server")));
1029                };
1030            } else {
1031                return Task::ready(Err(anyhow!("buffer does not have a language")));
1032            }
1033
1034            cx.spawn(|this, mut cx| async move {
1035                let response = lang_server
1036                    .request::<lsp::request::GotoDefinition>(lsp::GotoDefinitionParams {
1037                        text_document_position_params: lsp::TextDocumentPositionParams {
1038                            text_document: lsp::TextDocumentIdentifier::new(
1039                                lsp::Url::from_file_path(&buffer_abs_path).unwrap(),
1040                            ),
1041                            position: lsp::Position::new(point.row, point.column),
1042                        },
1043                        work_done_progress_params: Default::default(),
1044                        partial_result_params: Default::default(),
1045                    })
1046                    .await?;
1047
1048                let mut definitions = Vec::new();
1049                if let Some(response) = response {
1050                    let mut unresolved_locations = Vec::new();
1051                    match response {
1052                        lsp::GotoDefinitionResponse::Scalar(loc) => {
1053                            unresolved_locations.push((loc.uri, loc.range));
1054                        }
1055                        lsp::GotoDefinitionResponse::Array(locs) => {
1056                            unresolved_locations.extend(locs.into_iter().map(|l| (l.uri, l.range)));
1057                        }
1058                        lsp::GotoDefinitionResponse::Link(links) => {
1059                            unresolved_locations.extend(
1060                                links
1061                                    .into_iter()
1062                                    .map(|l| (l.target_uri, l.target_selection_range)),
1063                            );
1064                        }
1065                    }
1066
1067                    for (target_uri, target_range) in unresolved_locations {
1068                        let abs_path = target_uri
1069                            .to_file_path()
1070                            .map_err(|_| anyhow!("invalid target path"))?;
1071
1072                        let (worktree, relative_path) = if let Some(result) =
1073                            this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1074                        {
1075                            result
1076                        } else {
1077                            let worktree = this
1078                                .update(&mut cx, |this, cx| {
1079                                    this.create_local_worktree(&abs_path, true, cx)
1080                                })
1081                                .await?;
1082                            this.update(&mut cx, |this, cx| {
1083                                this.language_servers.insert(
1084                                    (worktree.read(cx).id(), lang_name.clone()),
1085                                    lang_server.clone(),
1086                                );
1087                            });
1088                            (worktree, PathBuf::new())
1089                        };
1090
1091                        let project_path = ProjectPath {
1092                            worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1093                            path: relative_path.into(),
1094                        };
1095                        let target_buffer_handle = this
1096                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1097                            .await?;
1098                        cx.read(|cx| {
1099                            let target_buffer = target_buffer_handle.read(cx);
1100                            let target_start = target_buffer
1101                                .clip_point_utf16(target_range.start.to_point_utf16(), Bias::Left);
1102                            let target_end = target_buffer
1103                                .clip_point_utf16(target_range.end.to_point_utf16(), Bias::Left);
1104                            definitions.push(Definition {
1105                                target_buffer: target_buffer_handle,
1106                                target_range: target_buffer.anchor_after(target_start)
1107                                    ..target_buffer.anchor_before(target_end),
1108                            });
1109                        });
1110                    }
1111                }
1112
1113                Ok(definitions)
1114            })
1115        } else if let Some(project_id) = self.remote_id() {
1116            let client = self.client.clone();
1117            let request = proto::GetDefinition {
1118                project_id,
1119                buffer_id: source_buffer.remote_id(),
1120                position: Some(serialize_anchor(&source_buffer.anchor_before(position))),
1121            };
1122            cx.spawn(|this, mut cx| async move {
1123                let response = client.request(request).await?;
1124                this.update(&mut cx, |this, cx| {
1125                    let mut definitions = Vec::new();
1126                    for definition in response.definitions {
1127                        let target_buffer = this.deserialize_remote_buffer(
1128                            definition.buffer.ok_or_else(|| anyhow!("missing buffer"))?,
1129                            cx,
1130                        )?;
1131                        let target_start = definition
1132                            .target_start
1133                            .and_then(deserialize_anchor)
1134                            .ok_or_else(|| anyhow!("missing target start"))?;
1135                        let target_end = definition
1136                            .target_end
1137                            .and_then(deserialize_anchor)
1138                            .ok_or_else(|| anyhow!("missing target end"))?;
1139                        definitions.push(Definition {
1140                            target_buffer,
1141                            target_range: target_start..target_end,
1142                        })
1143                    }
1144
1145                    Ok(definitions)
1146                })
1147            })
1148        } else {
1149            Task::ready(Err(anyhow!("project does not have a remote id")))
1150        }
1151    }
1152
1153    pub fn find_or_create_local_worktree(
1154        &self,
1155        abs_path: impl AsRef<Path>,
1156        weak: bool,
1157        cx: &mut ModelContext<Self>,
1158    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
1159        let abs_path = abs_path.as_ref();
1160        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
1161            Task::ready(Ok((tree.clone(), relative_path.into())))
1162        } else {
1163            let worktree = self.create_local_worktree(abs_path, weak, cx);
1164            cx.foreground()
1165                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
1166        }
1167    }
1168
1169    fn find_local_worktree(
1170        &self,
1171        abs_path: &Path,
1172        cx: &AppContext,
1173    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
1174        for tree in self.worktrees(cx) {
1175            if let Some(relative_path) = tree
1176                .read(cx)
1177                .as_local()
1178                .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
1179            {
1180                return Some((tree.clone(), relative_path.into()));
1181            }
1182        }
1183        None
1184    }
1185
1186    pub fn is_shared(&self) -> bool {
1187        match &self.client_state {
1188            ProjectClientState::Local { is_shared, .. } => *is_shared,
1189            ProjectClientState::Remote { .. } => false,
1190        }
1191    }
1192
1193    fn create_local_worktree(
1194        &self,
1195        abs_path: impl AsRef<Path>,
1196        weak: bool,
1197        cx: &mut ModelContext<Self>,
1198    ) -> Task<Result<ModelHandle<Worktree>>> {
1199        let fs = self.fs.clone();
1200        let client = self.client.clone();
1201        let path = Arc::from(abs_path.as_ref());
1202        cx.spawn(|project, mut cx| async move {
1203            let worktree = Worktree::local(client.clone(), path, weak, fs, &mut cx).await?;
1204
1205            let (remote_project_id, is_shared) = project.update(&mut cx, |project, cx| {
1206                project.add_worktree(&worktree, cx);
1207                (project.remote_id(), project.is_shared())
1208            });
1209
1210            if let Some(project_id) = remote_project_id {
1211                worktree
1212                    .update(&mut cx, |worktree, cx| {
1213                        worktree.as_local_mut().unwrap().register(project_id, cx)
1214                    })
1215                    .await?;
1216                if is_shared {
1217                    worktree
1218                        .update(&mut cx, |worktree, cx| {
1219                            worktree.as_local_mut().unwrap().share(project_id, cx)
1220                        })
1221                        .await?;
1222                }
1223            }
1224
1225            Ok(worktree)
1226        })
1227    }
1228
1229    pub fn remove_worktree(&mut self, id: WorktreeId, cx: &mut ModelContext<Self>) {
1230        self.worktrees.retain(|worktree| {
1231            worktree
1232                .upgrade(cx)
1233                .map_or(false, |w| w.read(cx).id() != id)
1234        });
1235        cx.notify();
1236    }
1237
1238    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
1239        cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
1240        if worktree.read(cx).is_local() {
1241            cx.subscribe(&worktree, |this, worktree, _, cx| {
1242                this.update_local_worktree_buffers(worktree, cx);
1243            })
1244            .detach();
1245        }
1246
1247        let push_weak_handle = {
1248            let worktree = worktree.read(cx);
1249            worktree.is_local() && worktree.is_weak()
1250        };
1251        if push_weak_handle {
1252            cx.observe_release(&worktree, |this, cx| {
1253                this.worktrees
1254                    .retain(|worktree| worktree.upgrade(cx).is_some());
1255                cx.notify();
1256            })
1257            .detach();
1258            self.worktrees
1259                .push(WorktreeHandle::Weak(worktree.downgrade()));
1260        } else {
1261            self.worktrees
1262                .push(WorktreeHandle::Strong(worktree.clone()));
1263        }
1264        cx.notify();
1265    }
1266
1267    fn update_local_worktree_buffers(
1268        &mut self,
1269        worktree_handle: ModelHandle<Worktree>,
1270        cx: &mut ModelContext<Self>,
1271    ) {
1272        let snapshot = worktree_handle.read(cx).snapshot();
1273        let mut buffers_to_delete = Vec::new();
1274        for (buffer_id, buffer) in &self.open_buffers {
1275            if let Some(buffer) = buffer.upgrade(cx) {
1276                buffer.update(cx, |buffer, cx| {
1277                    if let Some(old_file) = File::from_dyn(buffer.file()) {
1278                        if old_file.worktree != worktree_handle {
1279                            return;
1280                        }
1281
1282                        let new_file = if let Some(entry) = old_file
1283                            .entry_id
1284                            .and_then(|entry_id| snapshot.entry_for_id(entry_id))
1285                        {
1286                            File {
1287                                is_local: true,
1288                                entry_id: Some(entry.id),
1289                                mtime: entry.mtime,
1290                                path: entry.path.clone(),
1291                                worktree: worktree_handle.clone(),
1292                            }
1293                        } else if let Some(entry) =
1294                            snapshot.entry_for_path(old_file.path().as_ref())
1295                        {
1296                            File {
1297                                is_local: true,
1298                                entry_id: Some(entry.id),
1299                                mtime: entry.mtime,
1300                                path: entry.path.clone(),
1301                                worktree: worktree_handle.clone(),
1302                            }
1303                        } else {
1304                            File {
1305                                is_local: true,
1306                                entry_id: None,
1307                                path: old_file.path().clone(),
1308                                mtime: old_file.mtime(),
1309                                worktree: worktree_handle.clone(),
1310                            }
1311                        };
1312
1313                        if let Some(project_id) = self.remote_id() {
1314                            let client = self.client.clone();
1315                            let message = proto::UpdateBufferFile {
1316                                project_id,
1317                                buffer_id: *buffer_id as u64,
1318                                file: Some(new_file.to_proto()),
1319                            };
1320                            cx.foreground()
1321                                .spawn(async move { client.send(message).await })
1322                                .detach_and_log_err(cx);
1323                        }
1324                        buffer.file_updated(Box::new(new_file), cx).detach();
1325                    }
1326                });
1327            } else {
1328                buffers_to_delete.push(*buffer_id);
1329            }
1330        }
1331
1332        for buffer_id in buffers_to_delete {
1333            self.open_buffers.remove(&buffer_id);
1334        }
1335    }
1336
1337    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
1338        let new_active_entry = entry.and_then(|project_path| {
1339            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
1340            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
1341            Some(ProjectEntry {
1342                worktree_id: project_path.worktree_id,
1343                entry_id: entry.id,
1344            })
1345        });
1346        if new_active_entry != self.active_entry {
1347            self.active_entry = new_active_entry;
1348            cx.emit(Event::ActiveEntryChanged(new_active_entry));
1349        }
1350    }
1351
1352    pub fn is_running_disk_based_diagnostics(&self) -> bool {
1353        self.language_servers_with_diagnostics_running > 0
1354    }
1355
1356    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
1357        let mut summary = DiagnosticSummary::default();
1358        for (_, path_summary) in self.diagnostic_summaries(cx) {
1359            summary.error_count += path_summary.error_count;
1360            summary.warning_count += path_summary.warning_count;
1361            summary.info_count += path_summary.info_count;
1362            summary.hint_count += path_summary.hint_count;
1363        }
1364        summary
1365    }
1366
1367    pub fn diagnostic_summaries<'a>(
1368        &'a self,
1369        cx: &'a AppContext,
1370    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
1371        self.worktrees(cx).flat_map(move |worktree| {
1372            let worktree = worktree.read(cx);
1373            let worktree_id = worktree.id();
1374            worktree
1375                .diagnostic_summaries()
1376                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
1377        })
1378    }
1379
1380    pub fn disk_based_diagnostics_started(&mut self, cx: &mut ModelContext<Self>) {
1381        self.language_servers_with_diagnostics_running += 1;
1382        if self.language_servers_with_diagnostics_running == 1 {
1383            cx.emit(Event::DiskBasedDiagnosticsStarted);
1384        }
1385    }
1386
1387    pub fn disk_based_diagnostics_finished(&mut self, cx: &mut ModelContext<Self>) {
1388        cx.emit(Event::DiskBasedDiagnosticsUpdated);
1389        self.language_servers_with_diagnostics_running -= 1;
1390        if self.language_servers_with_diagnostics_running == 0 {
1391            cx.emit(Event::DiskBasedDiagnosticsFinished);
1392        }
1393    }
1394
1395    pub fn active_entry(&self) -> Option<ProjectEntry> {
1396        self.active_entry
1397    }
1398
1399    // RPC message handlers
1400
1401    fn handle_unshare_project(
1402        &mut self,
1403        _: TypedEnvelope<proto::UnshareProject>,
1404        _: Arc<Client>,
1405        cx: &mut ModelContext<Self>,
1406    ) -> Result<()> {
1407        if let ProjectClientState::Remote {
1408            sharing_has_stopped,
1409            ..
1410        } = &mut self.client_state
1411        {
1412            *sharing_has_stopped = true;
1413            self.collaborators.clear();
1414            cx.notify();
1415            Ok(())
1416        } else {
1417            unreachable!()
1418        }
1419    }
1420
1421    fn handle_add_collaborator(
1422        &mut self,
1423        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
1424        _: Arc<Client>,
1425        cx: &mut ModelContext<Self>,
1426    ) -> Result<()> {
1427        let user_store = self.user_store.clone();
1428        let collaborator = envelope
1429            .payload
1430            .collaborator
1431            .take()
1432            .ok_or_else(|| anyhow!("empty collaborator"))?;
1433
1434        cx.spawn(|this, mut cx| {
1435            async move {
1436                let collaborator =
1437                    Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
1438                this.update(&mut cx, |this, cx| {
1439                    this.collaborators
1440                        .insert(collaborator.peer_id, collaborator);
1441                    cx.notify();
1442                });
1443                Ok(())
1444            }
1445            .log_err()
1446        })
1447        .detach();
1448
1449        Ok(())
1450    }
1451
1452    fn handle_remove_collaborator(
1453        &mut self,
1454        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
1455        _: Arc<Client>,
1456        cx: &mut ModelContext<Self>,
1457    ) -> Result<()> {
1458        let peer_id = PeerId(envelope.payload.peer_id);
1459        let replica_id = self
1460            .collaborators
1461            .remove(&peer_id)
1462            .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
1463            .replica_id;
1464        self.shared_buffers.remove(&peer_id);
1465        for (_, buffer) in &self.open_buffers {
1466            if let Some(buffer) = buffer.upgrade(cx) {
1467                buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
1468            }
1469        }
1470        cx.notify();
1471        Ok(())
1472    }
1473
1474    fn handle_share_worktree(
1475        &mut self,
1476        envelope: TypedEnvelope<proto::ShareWorktree>,
1477        client: Arc<Client>,
1478        cx: &mut ModelContext<Self>,
1479    ) -> Result<()> {
1480        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
1481        let replica_id = self.replica_id();
1482        let worktree = envelope
1483            .payload
1484            .worktree
1485            .ok_or_else(|| anyhow!("invalid worktree"))?;
1486        let (worktree, load_task) = Worktree::remote(remote_id, replica_id, worktree, client, cx);
1487        self.add_worktree(&worktree, cx);
1488        load_task.detach();
1489        Ok(())
1490    }
1491
1492    fn handle_unregister_worktree(
1493        &mut self,
1494        envelope: TypedEnvelope<proto::UnregisterWorktree>,
1495        _: Arc<Client>,
1496        cx: &mut ModelContext<Self>,
1497    ) -> Result<()> {
1498        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1499        self.remove_worktree(worktree_id, cx);
1500        Ok(())
1501    }
1502
1503    fn handle_update_worktree(
1504        &mut self,
1505        envelope: TypedEnvelope<proto::UpdateWorktree>,
1506        _: Arc<Client>,
1507        cx: &mut ModelContext<Self>,
1508    ) -> Result<()> {
1509        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1510        if let Some(worktree) = self.worktree_for_id(worktree_id, cx) {
1511            worktree.update(cx, |worktree, cx| {
1512                let worktree = worktree.as_remote_mut().unwrap();
1513                worktree.update_from_remote(envelope, cx)
1514            })?;
1515        }
1516        Ok(())
1517    }
1518
1519    fn handle_update_diagnostic_summary(
1520        &mut self,
1521        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
1522        _: Arc<Client>,
1523        cx: &mut ModelContext<Self>,
1524    ) -> Result<()> {
1525        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1526        if let Some(worktree) = self.worktree_for_id(worktree_id, cx) {
1527            if let Some(summary) = envelope.payload.summary {
1528                let project_path = ProjectPath {
1529                    worktree_id,
1530                    path: Path::new(&summary.path).into(),
1531                };
1532                worktree.update(cx, |worktree, _| {
1533                    worktree
1534                        .as_remote_mut()
1535                        .unwrap()
1536                        .update_diagnostic_summary(project_path.path.clone(), &summary);
1537                });
1538                cx.emit(Event::DiagnosticsUpdated(project_path));
1539            }
1540        }
1541        Ok(())
1542    }
1543
1544    fn handle_disk_based_diagnostics_updating(
1545        &mut self,
1546        _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
1547        _: Arc<Client>,
1548        cx: &mut ModelContext<Self>,
1549    ) -> Result<()> {
1550        self.disk_based_diagnostics_started(cx);
1551        Ok(())
1552    }
1553
1554    fn handle_disk_based_diagnostics_updated(
1555        &mut self,
1556        _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
1557        _: Arc<Client>,
1558        cx: &mut ModelContext<Self>,
1559    ) -> Result<()> {
1560        self.disk_based_diagnostics_finished(cx);
1561        Ok(())
1562    }
1563
1564    pub fn handle_update_buffer(
1565        &mut self,
1566        envelope: TypedEnvelope<proto::UpdateBuffer>,
1567        _: Arc<Client>,
1568        cx: &mut ModelContext<Self>,
1569    ) -> Result<()> {
1570        let payload = envelope.payload.clone();
1571        let buffer_id = payload.buffer_id as usize;
1572        let ops = payload
1573            .operations
1574            .into_iter()
1575            .map(|op| language::proto::deserialize_operation(op))
1576            .collect::<Result<Vec<_>, _>>()?;
1577        if let Some(buffer) = self.open_buffers.get_mut(&buffer_id) {
1578            if let Some(buffer) = buffer.upgrade(cx) {
1579                buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
1580            }
1581        }
1582        Ok(())
1583    }
1584
1585    pub fn handle_update_buffer_file(
1586        &mut self,
1587        envelope: TypedEnvelope<proto::UpdateBufferFile>,
1588        _: Arc<Client>,
1589        cx: &mut ModelContext<Self>,
1590    ) -> Result<()> {
1591        let payload = envelope.payload.clone();
1592        let buffer_id = payload.buffer_id as usize;
1593        let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
1594        let worktree = self
1595            .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
1596            .ok_or_else(|| anyhow!("no such worktree"))?;
1597        let file = File::from_proto(file, worktree.clone(), cx)?;
1598        let buffer = self
1599            .open_buffers
1600            .get_mut(&buffer_id)
1601            .and_then(|b| b.upgrade(cx))
1602            .ok_or_else(|| anyhow!("no such buffer"))?;
1603        buffer.update(cx, |buffer, cx| {
1604            buffer.file_updated(Box::new(file), cx).detach();
1605        });
1606
1607        Ok(())
1608    }
1609
1610    pub fn handle_save_buffer(
1611        &mut self,
1612        envelope: TypedEnvelope<proto::SaveBuffer>,
1613        rpc: Arc<Client>,
1614        cx: &mut ModelContext<Self>,
1615    ) -> Result<()> {
1616        let sender_id = envelope.original_sender_id()?;
1617        let project_id = self.remote_id().ok_or_else(|| anyhow!("not connected"))?;
1618        let buffer = self
1619            .shared_buffers
1620            .get(&sender_id)
1621            .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
1622            .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
1623        let receipt = envelope.receipt();
1624        let buffer_id = envelope.payload.buffer_id;
1625        let save = cx.spawn(|_, mut cx| async move {
1626            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await
1627        });
1628
1629        cx.background()
1630            .spawn(
1631                async move {
1632                    let (version, mtime) = save.await?;
1633
1634                    rpc.respond(
1635                        receipt,
1636                        proto::BufferSaved {
1637                            project_id,
1638                            buffer_id,
1639                            version: (&version).into(),
1640                            mtime: Some(mtime.into()),
1641                        },
1642                    )
1643                    .await?;
1644
1645                    Ok(())
1646                }
1647                .log_err(),
1648            )
1649            .detach();
1650        Ok(())
1651    }
1652
1653    pub fn handle_format_buffer(
1654        &mut self,
1655        envelope: TypedEnvelope<proto::FormatBuffer>,
1656        rpc: Arc<Client>,
1657        cx: &mut ModelContext<Self>,
1658    ) -> Result<()> {
1659        let receipt = envelope.receipt();
1660        let sender_id = envelope.original_sender_id()?;
1661        let buffer = self
1662            .shared_buffers
1663            .get(&sender_id)
1664            .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
1665            .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
1666        cx.spawn(|_, mut cx| async move {
1667            let format = buffer.update(&mut cx, |buffer, cx| buffer.format(cx)).await;
1668            // We spawn here in order to enqueue the sending of `Ack` *after* transmission of edits
1669            // associated with formatting.
1670            cx.spawn(|_| async move {
1671                match format {
1672                    Ok(()) => rpc.respond(receipt, proto::Ack {}).await?,
1673                    Err(error) => {
1674                        rpc.respond_with_error(
1675                            receipt,
1676                            proto::Error {
1677                                message: error.to_string(),
1678                            },
1679                        )
1680                        .await?
1681                    }
1682                }
1683                Ok::<_, anyhow::Error>(())
1684            })
1685            .await
1686            .log_err();
1687        })
1688        .detach();
1689        Ok(())
1690    }
1691
1692    fn handle_get_completions(
1693        &mut self,
1694        envelope: TypedEnvelope<proto::GetCompletions>,
1695        rpc: Arc<Client>,
1696        cx: &mut ModelContext<Self>,
1697    ) -> Result<()> {
1698        let receipt = envelope.receipt();
1699        let sender_id = envelope.original_sender_id()?;
1700        let buffer = self
1701            .shared_buffers
1702            .get(&sender_id)
1703            .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
1704            .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
1705        let position = envelope
1706            .payload
1707            .position
1708            .and_then(language::proto::deserialize_anchor)
1709            .ok_or_else(|| anyhow!("invalid position"))?;
1710        cx.spawn(|_, mut cx| async move {
1711            match buffer
1712                .update(&mut cx, |buffer, cx| buffer.completions(position, cx))
1713                .await
1714            {
1715                Ok(completions) => {
1716                    rpc.respond(
1717                        receipt,
1718                        proto::GetCompletionsResponse {
1719                            completions: completions
1720                                .iter()
1721                                .map(language::proto::serialize_completion)
1722                                .collect(),
1723                        },
1724                    )
1725                    .await
1726                }
1727                Err(error) => {
1728                    rpc.respond_with_error(
1729                        receipt,
1730                        proto::Error {
1731                            message: error.to_string(),
1732                        },
1733                    )
1734                    .await
1735                }
1736            }
1737        })
1738        .detach_and_log_err(cx);
1739        Ok(())
1740    }
1741
1742    fn handle_apply_additional_edits_for_completion(
1743        &mut self,
1744        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
1745        rpc: Arc<Client>,
1746        cx: &mut ModelContext<Self>,
1747    ) -> Result<()> {
1748        let receipt = envelope.receipt();
1749        let sender_id = envelope.original_sender_id()?;
1750        let buffer = self
1751            .shared_buffers
1752            .get(&sender_id)
1753            .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
1754            .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
1755        let language = buffer.read(cx).language();
1756        let completion = language::proto::deserialize_completion(
1757            envelope
1758                .payload
1759                .completion
1760                .ok_or_else(|| anyhow!("invalid position"))?,
1761            language,
1762        )?;
1763        cx.spawn(|_, mut cx| async move {
1764            match buffer
1765                .update(&mut cx, |buffer, cx| {
1766                    buffer.apply_additional_edits_for_completion(completion, false, cx)
1767                })
1768                .await
1769            {
1770                Ok(edit_ids) => {
1771                    rpc.respond(
1772                        receipt,
1773                        proto::ApplyCompletionAdditionalEditsResponse {
1774                            additional_edits: edit_ids
1775                                .into_iter()
1776                                .map(|edit_id| proto::AdditionalEdit {
1777                                    replica_id: edit_id.replica_id as u32,
1778                                    local_timestamp: edit_id.value,
1779                                })
1780                                .collect(),
1781                        },
1782                    )
1783                    .await
1784                }
1785                Err(error) => {
1786                    rpc.respond_with_error(
1787                        receipt,
1788                        proto::Error {
1789                            message: error.to_string(),
1790                        },
1791                    )
1792                    .await
1793                }
1794            }
1795        })
1796        .detach_and_log_err(cx);
1797        Ok(())
1798    }
1799
1800    pub fn handle_get_definition(
1801        &mut self,
1802        envelope: TypedEnvelope<proto::GetDefinition>,
1803        rpc: Arc<Client>,
1804        cx: &mut ModelContext<Self>,
1805    ) -> Result<()> {
1806        let receipt = envelope.receipt();
1807        let sender_id = envelope.original_sender_id()?;
1808        let source_buffer = self
1809            .shared_buffers
1810            .get(&sender_id)
1811            .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
1812            .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
1813        let position = envelope
1814            .payload
1815            .position
1816            .and_then(deserialize_anchor)
1817            .ok_or_else(|| anyhow!("invalid position"))?;
1818        if !source_buffer.read(cx).can_resolve(&position) {
1819            return Err(anyhow!("cannot resolve position"));
1820        }
1821
1822        let definitions = self.definition(&source_buffer, position, cx);
1823        cx.spawn(|this, mut cx| async move {
1824            let definitions = definitions.await?;
1825            let mut response = proto::GetDefinitionResponse {
1826                definitions: Default::default(),
1827            };
1828            this.update(&mut cx, |this, cx| {
1829                for definition in definitions {
1830                    let buffer =
1831                        this.serialize_buffer_for_peer(&definition.target_buffer, sender_id, cx);
1832                    response.definitions.push(proto::Definition {
1833                        target_start: Some(serialize_anchor(&definition.target_range.start)),
1834                        target_end: Some(serialize_anchor(&definition.target_range.end)),
1835                        buffer: Some(buffer),
1836                    });
1837                }
1838            });
1839            rpc.respond(receipt, response).await?;
1840            Ok::<_, anyhow::Error>(())
1841        })
1842        .detach_and_log_err(cx);
1843
1844        Ok(())
1845    }
1846
1847    pub fn handle_open_buffer(
1848        &mut self,
1849        envelope: TypedEnvelope<proto::OpenBuffer>,
1850        rpc: Arc<Client>,
1851        cx: &mut ModelContext<Self>,
1852    ) -> anyhow::Result<()> {
1853        let receipt = envelope.receipt();
1854        let peer_id = envelope.original_sender_id()?;
1855        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1856        let open_buffer = self.open_buffer(
1857            ProjectPath {
1858                worktree_id,
1859                path: PathBuf::from(envelope.payload.path).into(),
1860            },
1861            cx,
1862        );
1863        cx.spawn(|this, mut cx| {
1864            async move {
1865                let buffer = open_buffer.await?;
1866                let buffer = this.update(&mut cx, |this, cx| {
1867                    this.serialize_buffer_for_peer(&buffer, peer_id, cx)
1868                });
1869                rpc.respond(
1870                    receipt,
1871                    proto::OpenBufferResponse {
1872                        buffer: Some(buffer),
1873                    },
1874                )
1875                .await
1876            }
1877            .log_err()
1878        })
1879        .detach();
1880        Ok(())
1881    }
1882
1883    fn serialize_buffer_for_peer(
1884        &mut self,
1885        buffer: &ModelHandle<Buffer>,
1886        peer_id: PeerId,
1887        cx: &AppContext,
1888    ) -> proto::Buffer {
1889        let buffer_id = buffer.read(cx).remote_id();
1890        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
1891        match shared_buffers.entry(buffer_id) {
1892            hash_map::Entry::Occupied(_) => proto::Buffer {
1893                variant: Some(proto::buffer::Variant::Id(buffer_id)),
1894            },
1895            hash_map::Entry::Vacant(entry) => {
1896                entry.insert(buffer.clone());
1897                proto::Buffer {
1898                    variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
1899                }
1900            }
1901        }
1902    }
1903
1904    fn deserialize_remote_buffer(
1905        &mut self,
1906        buffer: proto::Buffer,
1907        cx: &mut ModelContext<Self>,
1908    ) -> Result<ModelHandle<Buffer>> {
1909        match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
1910            proto::buffer::Variant::Id(id) => self
1911                .open_buffers
1912                .get(&(id as usize))
1913                .and_then(|buffer| buffer.upgrade(cx))
1914                .ok_or_else(|| anyhow!("no buffer exists for id {}", id)),
1915            proto::buffer::Variant::State(mut buffer) => {
1916                let mut buffer_worktree = None;
1917                let mut buffer_file = None;
1918                if let Some(file) = buffer.file.take() {
1919                    let worktree_id = WorktreeId::from_proto(file.worktree_id);
1920                    let worktree = self
1921                        .worktree_for_id(worktree_id, cx)
1922                        .ok_or_else(|| anyhow!("no worktree found for id {}", file.worktree_id))?;
1923                    buffer_file = Some(Box::new(File::from_proto(file, worktree.clone(), cx)?)
1924                        as Box<dyn language::File>);
1925                    buffer_worktree = Some(worktree);
1926                }
1927
1928                let buffer = cx.add_model(|cx| {
1929                    Buffer::from_proto(self.replica_id(), buffer, buffer_file, cx).unwrap()
1930                });
1931                self.register_buffer(&buffer, buffer_worktree.as_ref(), cx)?;
1932                Ok(buffer)
1933            }
1934        }
1935    }
1936
1937    pub fn handle_close_buffer(
1938        &mut self,
1939        envelope: TypedEnvelope<proto::CloseBuffer>,
1940        _: Arc<Client>,
1941        cx: &mut ModelContext<Self>,
1942    ) -> anyhow::Result<()> {
1943        if let Some(shared_buffers) = self.shared_buffers.get_mut(&envelope.original_sender_id()?) {
1944            shared_buffers.remove(&envelope.payload.buffer_id);
1945            cx.notify();
1946        }
1947        Ok(())
1948    }
1949
1950    pub fn handle_buffer_saved(
1951        &mut self,
1952        envelope: TypedEnvelope<proto::BufferSaved>,
1953        _: Arc<Client>,
1954        cx: &mut ModelContext<Self>,
1955    ) -> Result<()> {
1956        let payload = envelope.payload.clone();
1957        let buffer = self
1958            .open_buffers
1959            .get(&(payload.buffer_id as usize))
1960            .and_then(|buffer| buffer.upgrade(cx));
1961        if let Some(buffer) = buffer {
1962            buffer.update(cx, |buffer, cx| {
1963                let version = payload.version.try_into()?;
1964                let mtime = payload
1965                    .mtime
1966                    .ok_or_else(|| anyhow!("missing mtime"))?
1967                    .into();
1968                buffer.did_save(version, mtime, None, cx);
1969                Result::<_, anyhow::Error>::Ok(())
1970            })?;
1971        }
1972        Ok(())
1973    }
1974
1975    pub fn handle_buffer_reloaded(
1976        &mut self,
1977        envelope: TypedEnvelope<proto::BufferReloaded>,
1978        _: Arc<Client>,
1979        cx: &mut ModelContext<Self>,
1980    ) -> Result<()> {
1981        let payload = envelope.payload.clone();
1982        let buffer = self
1983            .open_buffers
1984            .get(&(payload.buffer_id as usize))
1985            .and_then(|buffer| buffer.upgrade(cx));
1986        if let Some(buffer) = buffer {
1987            buffer.update(cx, |buffer, cx| {
1988                let version = payload.version.try_into()?;
1989                let mtime = payload
1990                    .mtime
1991                    .ok_or_else(|| anyhow!("missing mtime"))?
1992                    .into();
1993                buffer.did_reload(version, mtime, cx);
1994                Result::<_, anyhow::Error>::Ok(())
1995            })?;
1996        }
1997        Ok(())
1998    }
1999
2000    pub fn match_paths<'a>(
2001        &self,
2002        query: &'a str,
2003        include_ignored: bool,
2004        smart_case: bool,
2005        max_results: usize,
2006        cancel_flag: &'a AtomicBool,
2007        cx: &AppContext,
2008    ) -> impl 'a + Future<Output = Vec<PathMatch>> {
2009        let worktrees = self
2010            .worktrees(cx)
2011            .filter(|worktree| !worktree.read(cx).is_weak())
2012            .collect::<Vec<_>>();
2013        let include_root_name = worktrees.len() > 1;
2014        let candidate_sets = worktrees
2015            .into_iter()
2016            .map(|worktree| CandidateSet {
2017                snapshot: worktree.read(cx).snapshot(),
2018                include_ignored,
2019                include_root_name,
2020            })
2021            .collect::<Vec<_>>();
2022
2023        let background = cx.background().clone();
2024        async move {
2025            fuzzy::match_paths(
2026                candidate_sets.as_slice(),
2027                query,
2028                smart_case,
2029                max_results,
2030                cancel_flag,
2031                background,
2032            )
2033            .await
2034        }
2035    }
2036}
2037
2038impl WorktreeHandle {
2039    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
2040        match self {
2041            WorktreeHandle::Strong(handle) => Some(handle.clone()),
2042            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
2043        }
2044    }
2045}
2046
2047struct CandidateSet {
2048    snapshot: Snapshot,
2049    include_ignored: bool,
2050    include_root_name: bool,
2051}
2052
2053impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
2054    type Candidates = CandidateSetIter<'a>;
2055
2056    fn id(&self) -> usize {
2057        self.snapshot.id().to_usize()
2058    }
2059
2060    fn len(&self) -> usize {
2061        if self.include_ignored {
2062            self.snapshot.file_count()
2063        } else {
2064            self.snapshot.visible_file_count()
2065        }
2066    }
2067
2068    fn prefix(&self) -> Arc<str> {
2069        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
2070            self.snapshot.root_name().into()
2071        } else if self.include_root_name {
2072            format!("{}/", self.snapshot.root_name()).into()
2073        } else {
2074            "".into()
2075        }
2076    }
2077
2078    fn candidates(&'a self, start: usize) -> Self::Candidates {
2079        CandidateSetIter {
2080            traversal: self.snapshot.files(self.include_ignored, start),
2081        }
2082    }
2083}
2084
2085struct CandidateSetIter<'a> {
2086    traversal: Traversal<'a>,
2087}
2088
2089impl<'a> Iterator for CandidateSetIter<'a> {
2090    type Item = PathMatchCandidate<'a>;
2091
2092    fn next(&mut self) -> Option<Self::Item> {
2093        self.traversal.next().map(|entry| {
2094            if let EntryKind::File(char_bag) = entry.kind {
2095                PathMatchCandidate {
2096                    path: &entry.path,
2097                    char_bag,
2098                }
2099            } else {
2100                unreachable!()
2101            }
2102        })
2103    }
2104}
2105
2106impl Entity for Project {
2107    type Event = Event;
2108
2109    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
2110        match &self.client_state {
2111            ProjectClientState::Local { remote_id_rx, .. } => {
2112                if let Some(project_id) = *remote_id_rx.borrow() {
2113                    let rpc = self.client.clone();
2114                    cx.spawn(|_| async move {
2115                        if let Err(err) = rpc.send(proto::UnregisterProject { project_id }).await {
2116                            log::error!("error unregistering project: {}", err);
2117                        }
2118                    })
2119                    .detach();
2120                }
2121            }
2122            ProjectClientState::Remote { remote_id, .. } => {
2123                let rpc = self.client.clone();
2124                let project_id = *remote_id;
2125                cx.spawn(|_| async move {
2126                    if let Err(err) = rpc.send(proto::LeaveProject { project_id }).await {
2127                        log::error!("error leaving project: {}", err);
2128                    }
2129                })
2130                .detach();
2131            }
2132        }
2133    }
2134
2135    fn app_will_quit(
2136        &mut self,
2137        _: &mut MutableAppContext,
2138    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
2139        use futures::FutureExt;
2140
2141        let shutdown_futures = self
2142            .language_servers
2143            .drain()
2144            .filter_map(|(_, server)| server.shutdown())
2145            .collect::<Vec<_>>();
2146        Some(
2147            async move {
2148                futures::future::join_all(shutdown_futures).await;
2149            }
2150            .boxed(),
2151        )
2152    }
2153}
2154
2155impl Collaborator {
2156    fn from_proto(
2157        message: proto::Collaborator,
2158        user_store: &ModelHandle<UserStore>,
2159        cx: &mut AsyncAppContext,
2160    ) -> impl Future<Output = Result<Self>> {
2161        let user = user_store.update(cx, |user_store, cx| {
2162            user_store.fetch_user(message.user_id, cx)
2163        });
2164
2165        async move {
2166            Ok(Self {
2167                peer_id: PeerId(message.peer_id),
2168                user: user.await?,
2169                replica_id: message.replica_id as ReplicaId,
2170            })
2171        }
2172    }
2173}
2174
2175impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
2176    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
2177        Self {
2178            worktree_id,
2179            path: path.as_ref().into(),
2180        }
2181    }
2182}
2183
2184#[cfg(test)]
2185mod tests {
2186    use super::{Event, *};
2187    use client::test::FakeHttpClient;
2188    use fs::RealFs;
2189    use futures::StreamExt;
2190    use gpui::{test::subscribe, TestAppContext};
2191    use language::{
2192        tree_sitter_rust, AnchorRangeExt, Diagnostic, LanguageConfig, LanguageRegistry,
2193        LanguageServerConfig, Point,
2194    };
2195    use lsp::Url;
2196    use serde_json::json;
2197    use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc};
2198    use unindent::Unindent as _;
2199    use util::test::temp_tree;
2200    use worktree::WorktreeHandle as _;
2201
2202    #[gpui::test]
2203    async fn test_populate_and_search(mut cx: gpui::TestAppContext) {
2204        let dir = temp_tree(json!({
2205            "root": {
2206                "apple": "",
2207                "banana": {
2208                    "carrot": {
2209                        "date": "",
2210                        "endive": "",
2211                    }
2212                },
2213                "fennel": {
2214                    "grape": "",
2215                }
2216            }
2217        }));
2218
2219        let root_link_path = dir.path().join("root_link");
2220        unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
2221        unix::fs::symlink(
2222            &dir.path().join("root/fennel"),
2223            &dir.path().join("root/finnochio"),
2224        )
2225        .unwrap();
2226
2227        let project = build_project(Arc::new(RealFs), &mut cx);
2228
2229        let (tree, _) = project
2230            .update(&mut cx, |project, cx| {
2231                project.find_or_create_local_worktree(&root_link_path, false, cx)
2232            })
2233            .await
2234            .unwrap();
2235
2236        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2237            .await;
2238        cx.read(|cx| {
2239            let tree = tree.read(cx);
2240            assert_eq!(tree.file_count(), 5);
2241            assert_eq!(
2242                tree.inode_for_path("fennel/grape"),
2243                tree.inode_for_path("finnochio/grape")
2244            );
2245        });
2246
2247        let cancel_flag = Default::default();
2248        let results = project
2249            .read_with(&cx, |project, cx| {
2250                project.match_paths("bna", false, false, 10, &cancel_flag, cx)
2251            })
2252            .await;
2253        assert_eq!(
2254            results
2255                .into_iter()
2256                .map(|result| result.path)
2257                .collect::<Vec<Arc<Path>>>(),
2258            vec![
2259                PathBuf::from("banana/carrot/date").into(),
2260                PathBuf::from("banana/carrot/endive").into(),
2261            ]
2262        );
2263    }
2264
2265    #[gpui::test]
2266    async fn test_language_server_diagnostics(mut cx: gpui::TestAppContext) {
2267        let (language_server_config, mut fake_server) =
2268            LanguageServerConfig::fake(cx.background()).await;
2269        let progress_token = language_server_config
2270            .disk_based_diagnostics_progress_token
2271            .clone()
2272            .unwrap();
2273
2274        let mut languages = LanguageRegistry::new();
2275        languages.add(Arc::new(Language::new(
2276            LanguageConfig {
2277                name: "Rust".to_string(),
2278                path_suffixes: vec!["rs".to_string()],
2279                language_server: Some(language_server_config),
2280                ..Default::default()
2281            },
2282            Some(tree_sitter_rust::language()),
2283        )));
2284
2285        let dir = temp_tree(json!({
2286            "a.rs": "fn a() { A }",
2287            "b.rs": "const y: i32 = 1",
2288        }));
2289
2290        let http_client = FakeHttpClient::with_404_response();
2291        let client = Client::new(http_client.clone());
2292        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
2293
2294        let project = cx.update(|cx| {
2295            Project::local(
2296                client,
2297                user_store,
2298                Arc::new(languages),
2299                Arc::new(RealFs),
2300                cx,
2301            )
2302        });
2303
2304        let (tree, _) = project
2305            .update(&mut cx, |project, cx| {
2306                project.find_or_create_local_worktree(dir.path(), false, cx)
2307            })
2308            .await
2309            .unwrap();
2310        let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
2311
2312        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2313            .await;
2314
2315        // Cause worktree to start the fake language server
2316        let _buffer = project
2317            .update(&mut cx, |project, cx| {
2318                project.open_buffer(
2319                    ProjectPath {
2320                        worktree_id,
2321                        path: Path::new("b.rs").into(),
2322                    },
2323                    cx,
2324                )
2325            })
2326            .await
2327            .unwrap();
2328
2329        let mut events = subscribe(&project, &mut cx);
2330
2331        fake_server.start_progress(&progress_token).await;
2332        assert_eq!(
2333            events.next().await.unwrap(),
2334            Event::DiskBasedDiagnosticsStarted
2335        );
2336
2337        fake_server.start_progress(&progress_token).await;
2338        fake_server.end_progress(&progress_token).await;
2339        fake_server.start_progress(&progress_token).await;
2340
2341        fake_server
2342            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
2343                uri: Url::from_file_path(dir.path().join("a.rs")).unwrap(),
2344                version: None,
2345                diagnostics: vec![lsp::Diagnostic {
2346                    range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
2347                    severity: Some(lsp::DiagnosticSeverity::ERROR),
2348                    message: "undefined variable 'A'".to_string(),
2349                    ..Default::default()
2350                }],
2351            })
2352            .await;
2353        assert_eq!(
2354            events.next().await.unwrap(),
2355            Event::DiagnosticsUpdated(ProjectPath {
2356                worktree_id,
2357                path: Arc::from(Path::new("a.rs"))
2358            })
2359        );
2360
2361        fake_server.end_progress(&progress_token).await;
2362        fake_server.end_progress(&progress_token).await;
2363        assert_eq!(
2364            events.next().await.unwrap(),
2365            Event::DiskBasedDiagnosticsUpdated
2366        );
2367        assert_eq!(
2368            events.next().await.unwrap(),
2369            Event::DiskBasedDiagnosticsFinished
2370        );
2371
2372        let buffer = project
2373            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
2374            .await
2375            .unwrap();
2376
2377        buffer.read_with(&cx, |buffer, _| {
2378            let snapshot = buffer.snapshot();
2379            let diagnostics = snapshot
2380                .diagnostics_in_range::<_, Point>(0..buffer.len())
2381                .collect::<Vec<_>>();
2382            assert_eq!(
2383                diagnostics,
2384                &[DiagnosticEntry {
2385                    range: Point::new(0, 9)..Point::new(0, 10),
2386                    diagnostic: Diagnostic {
2387                        severity: lsp::DiagnosticSeverity::ERROR,
2388                        message: "undefined variable 'A'".to_string(),
2389                        group_id: 0,
2390                        is_primary: true,
2391                        ..Default::default()
2392                    }
2393                }]
2394            )
2395        });
2396    }
2397
2398    #[gpui::test]
2399    async fn test_search_worktree_without_files(mut cx: gpui::TestAppContext) {
2400        let dir = temp_tree(json!({
2401            "root": {
2402                "dir1": {},
2403                "dir2": {
2404                    "dir3": {}
2405                }
2406            }
2407        }));
2408
2409        let project = build_project(Arc::new(RealFs), &mut cx);
2410        let (tree, _) = project
2411            .update(&mut cx, |project, cx| {
2412                project.find_or_create_local_worktree(&dir.path(), false, cx)
2413            })
2414            .await
2415            .unwrap();
2416
2417        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2418            .await;
2419
2420        let cancel_flag = Default::default();
2421        let results = project
2422            .read_with(&cx, |project, cx| {
2423                project.match_paths("dir", false, false, 10, &cancel_flag, cx)
2424            })
2425            .await;
2426
2427        assert!(results.is_empty());
2428    }
2429
2430    #[gpui::test]
2431    async fn test_definition(mut cx: gpui::TestAppContext) {
2432        let (language_server_config, mut fake_server) =
2433            LanguageServerConfig::fake(cx.background()).await;
2434
2435        let mut languages = LanguageRegistry::new();
2436        languages.add(Arc::new(Language::new(
2437            LanguageConfig {
2438                name: "Rust".to_string(),
2439                path_suffixes: vec!["rs".to_string()],
2440                language_server: Some(language_server_config),
2441                ..Default::default()
2442            },
2443            Some(tree_sitter_rust::language()),
2444        )));
2445
2446        let dir = temp_tree(json!({
2447            "a.rs": "const fn a() { A }",
2448            "b.rs": "const y: i32 = crate::a()",
2449        }));
2450
2451        let http_client = FakeHttpClient::with_404_response();
2452        let client = Client::new(http_client.clone());
2453        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
2454        let project = cx.update(|cx| {
2455            Project::local(
2456                client,
2457                user_store,
2458                Arc::new(languages),
2459                Arc::new(RealFs),
2460                cx,
2461            )
2462        });
2463
2464        let (tree, _) = project
2465            .update(&mut cx, |project, cx| {
2466                project.find_or_create_local_worktree(dir.path().join("b.rs"), false, cx)
2467            })
2468            .await
2469            .unwrap();
2470        let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
2471        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2472            .await;
2473
2474        // Cause worktree to start the fake language server
2475        let buffer = project
2476            .update(&mut cx, |project, cx| {
2477                project.open_buffer(
2478                    ProjectPath {
2479                        worktree_id,
2480                        path: Path::new("").into(),
2481                    },
2482                    cx,
2483                )
2484            })
2485            .await
2486            .unwrap();
2487        let definitions =
2488            project.update(&mut cx, |project, cx| project.definition(&buffer, 22, cx));
2489        let (request_id, request) = fake_server
2490            .receive_request::<lsp::request::GotoDefinition>()
2491            .await;
2492        let request_params = request.text_document_position_params;
2493        assert_eq!(
2494            request_params.text_document.uri.to_file_path().unwrap(),
2495            dir.path().join("b.rs")
2496        );
2497        assert_eq!(request_params.position, lsp::Position::new(0, 22));
2498
2499        fake_server
2500            .respond(
2501                request_id,
2502                Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
2503                    lsp::Url::from_file_path(dir.path().join("a.rs")).unwrap(),
2504                    lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
2505                ))),
2506            )
2507            .await;
2508        let mut definitions = definitions.await.unwrap();
2509        assert_eq!(definitions.len(), 1);
2510        let definition = definitions.pop().unwrap();
2511        cx.update(|cx| {
2512            let target_buffer = definition.target_buffer.read(cx);
2513            assert_eq!(
2514                target_buffer
2515                    .file()
2516                    .unwrap()
2517                    .as_local()
2518                    .unwrap()
2519                    .abs_path(cx),
2520                dir.path().join("a.rs")
2521            );
2522            assert_eq!(definition.target_range.to_offset(target_buffer), 9..10);
2523            assert_eq!(
2524                list_worktrees(&project, cx),
2525                [
2526                    (dir.path().join("b.rs"), false),
2527                    (dir.path().join("a.rs"), true)
2528                ]
2529            );
2530
2531            drop(definition);
2532        });
2533        cx.read(|cx| {
2534            assert_eq!(
2535                list_worktrees(&project, cx),
2536                [(dir.path().join("b.rs"), false)]
2537            );
2538        });
2539
2540        fn list_worktrees(project: &ModelHandle<Project>, cx: &AppContext) -> Vec<(PathBuf, bool)> {
2541            project
2542                .read(cx)
2543                .worktrees(cx)
2544                .map(|worktree| {
2545                    let worktree = worktree.read(cx);
2546                    (
2547                        worktree.as_local().unwrap().abs_path().to_path_buf(),
2548                        worktree.is_weak(),
2549                    )
2550                })
2551                .collect::<Vec<_>>()
2552        }
2553    }
2554
2555    #[gpui::test]
2556    async fn test_save_file(mut cx: gpui::TestAppContext) {
2557        let fs = Arc::new(FakeFs::new(cx.background()));
2558        fs.insert_tree(
2559            "/dir",
2560            json!({
2561                "file1": "the old contents",
2562            }),
2563        )
2564        .await;
2565
2566        let project = build_project(fs.clone(), &mut cx);
2567        let worktree_id = project
2568            .update(&mut cx, |p, cx| {
2569                p.find_or_create_local_worktree("/dir", false, cx)
2570            })
2571            .await
2572            .unwrap()
2573            .0
2574            .read_with(&cx, |tree, _| tree.id());
2575
2576        let buffer = project
2577            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
2578            .await
2579            .unwrap();
2580        buffer
2581            .update(&mut cx, |buffer, cx| {
2582                assert_eq!(buffer.text(), "the old contents");
2583                buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
2584                buffer.save(cx)
2585            })
2586            .await
2587            .unwrap();
2588
2589        let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
2590        assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
2591    }
2592
2593    #[gpui::test]
2594    async fn test_save_in_single_file_worktree(mut cx: gpui::TestAppContext) {
2595        let fs = Arc::new(FakeFs::new(cx.background()));
2596        fs.insert_tree(
2597            "/dir",
2598            json!({
2599                "file1": "the old contents",
2600            }),
2601        )
2602        .await;
2603
2604        let project = build_project(fs.clone(), &mut cx);
2605        let worktree_id = project
2606            .update(&mut cx, |p, cx| {
2607                p.find_or_create_local_worktree("/dir/file1", false, cx)
2608            })
2609            .await
2610            .unwrap()
2611            .0
2612            .read_with(&cx, |tree, _| tree.id());
2613
2614        let buffer = project
2615            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, ""), cx))
2616            .await
2617            .unwrap();
2618        buffer
2619            .update(&mut cx, |buffer, cx| {
2620                buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
2621                buffer.save(cx)
2622            })
2623            .await
2624            .unwrap();
2625
2626        let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
2627        assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
2628    }
2629
2630    #[gpui::test(retries = 5)]
2631    async fn test_rescan_and_remote_updates(mut cx: gpui::TestAppContext) {
2632        let dir = temp_tree(json!({
2633            "a": {
2634                "file1": "",
2635                "file2": "",
2636                "file3": "",
2637            },
2638            "b": {
2639                "c": {
2640                    "file4": "",
2641                    "file5": "",
2642                }
2643            }
2644        }));
2645
2646        let project = build_project(Arc::new(RealFs), &mut cx);
2647        let rpc = project.read_with(&cx, |p, _| p.client.clone());
2648
2649        let (tree, _) = project
2650            .update(&mut cx, |p, cx| {
2651                p.find_or_create_local_worktree(dir.path(), false, cx)
2652            })
2653            .await
2654            .unwrap();
2655        let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
2656
2657        let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
2658            let buffer = project.update(cx, |p, cx| p.open_buffer((worktree_id, path), cx));
2659            async move { buffer.await.unwrap() }
2660        };
2661        let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
2662            tree.read_with(cx, |tree, _| {
2663                tree.entry_for_path(path)
2664                    .expect(&format!("no entry for path {}", path))
2665                    .id
2666            })
2667        };
2668
2669        let buffer2 = buffer_for_path("a/file2", &mut cx).await;
2670        let buffer3 = buffer_for_path("a/file3", &mut cx).await;
2671        let buffer4 = buffer_for_path("b/c/file4", &mut cx).await;
2672        let buffer5 = buffer_for_path("b/c/file5", &mut cx).await;
2673
2674        let file2_id = id_for_path("a/file2", &cx);
2675        let file3_id = id_for_path("a/file3", &cx);
2676        let file4_id = id_for_path("b/c/file4", &cx);
2677
2678        // Wait for the initial scan.
2679        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
2680            .await;
2681
2682        // Create a remote copy of this worktree.
2683        let initial_snapshot = tree.read_with(&cx, |tree, _| tree.snapshot());
2684        let (remote, load_task) = cx.update(|cx| {
2685            Worktree::remote(
2686                1,
2687                1,
2688                initial_snapshot.to_proto(&Default::default(), Default::default()),
2689                rpc.clone(),
2690                cx,
2691            )
2692        });
2693        load_task.await;
2694
2695        cx.read(|cx| {
2696            assert!(!buffer2.read(cx).is_dirty());
2697            assert!(!buffer3.read(cx).is_dirty());
2698            assert!(!buffer4.read(cx).is_dirty());
2699            assert!(!buffer5.read(cx).is_dirty());
2700        });
2701
2702        // Rename and delete files and directories.
2703        tree.flush_fs_events(&cx).await;
2704        std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
2705        std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
2706        std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
2707        std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
2708        tree.flush_fs_events(&cx).await;
2709
2710        let expected_paths = vec![
2711            "a",
2712            "a/file1",
2713            "a/file2.new",
2714            "b",
2715            "d",
2716            "d/file3",
2717            "d/file4",
2718        ];
2719
2720        cx.read(|app| {
2721            assert_eq!(
2722                tree.read(app)
2723                    .paths()
2724                    .map(|p| p.to_str().unwrap())
2725                    .collect::<Vec<_>>(),
2726                expected_paths
2727            );
2728
2729            assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
2730            assert_eq!(id_for_path("d/file3", &cx), file3_id);
2731            assert_eq!(id_for_path("d/file4", &cx), file4_id);
2732
2733            assert_eq!(
2734                buffer2.read(app).file().unwrap().path().as_ref(),
2735                Path::new("a/file2.new")
2736            );
2737            assert_eq!(
2738                buffer3.read(app).file().unwrap().path().as_ref(),
2739                Path::new("d/file3")
2740            );
2741            assert_eq!(
2742                buffer4.read(app).file().unwrap().path().as_ref(),
2743                Path::new("d/file4")
2744            );
2745            assert_eq!(
2746                buffer5.read(app).file().unwrap().path().as_ref(),
2747                Path::new("b/c/file5")
2748            );
2749
2750            assert!(!buffer2.read(app).file().unwrap().is_deleted());
2751            assert!(!buffer3.read(app).file().unwrap().is_deleted());
2752            assert!(!buffer4.read(app).file().unwrap().is_deleted());
2753            assert!(buffer5.read(app).file().unwrap().is_deleted());
2754        });
2755
2756        // Update the remote worktree. Check that it becomes consistent with the
2757        // local worktree.
2758        remote.update(&mut cx, |remote, cx| {
2759            let update_message =
2760                tree.read(cx)
2761                    .snapshot()
2762                    .build_update(&initial_snapshot, 1, 1, true);
2763            remote
2764                .as_remote_mut()
2765                .unwrap()
2766                .snapshot
2767                .apply_remote_update(update_message)
2768                .unwrap();
2769
2770            assert_eq!(
2771                remote
2772                    .paths()
2773                    .map(|p| p.to_str().unwrap())
2774                    .collect::<Vec<_>>(),
2775                expected_paths
2776            );
2777        });
2778    }
2779
2780    #[gpui::test]
2781    async fn test_buffer_deduping(mut cx: gpui::TestAppContext) {
2782        let fs = Arc::new(FakeFs::new(cx.background()));
2783        fs.insert_tree(
2784            "/the-dir",
2785            json!({
2786                "a.txt": "a-contents",
2787                "b.txt": "b-contents",
2788            }),
2789        )
2790        .await;
2791
2792        let project = build_project(fs.clone(), &mut cx);
2793        let worktree_id = project
2794            .update(&mut cx, |p, cx| {
2795                p.find_or_create_local_worktree("/the-dir", false, cx)
2796            })
2797            .await
2798            .unwrap()
2799            .0
2800            .read_with(&cx, |tree, _| tree.id());
2801
2802        // Spawn multiple tasks to open paths, repeating some paths.
2803        let (buffer_a_1, buffer_b, buffer_a_2) = project.update(&mut cx, |p, cx| {
2804            (
2805                p.open_buffer((worktree_id, "a.txt"), cx),
2806                p.open_buffer((worktree_id, "b.txt"), cx),
2807                p.open_buffer((worktree_id, "a.txt"), cx),
2808            )
2809        });
2810
2811        let buffer_a_1 = buffer_a_1.await.unwrap();
2812        let buffer_a_2 = buffer_a_2.await.unwrap();
2813        let buffer_b = buffer_b.await.unwrap();
2814        assert_eq!(buffer_a_1.read_with(&cx, |b, _| b.text()), "a-contents");
2815        assert_eq!(buffer_b.read_with(&cx, |b, _| b.text()), "b-contents");
2816
2817        // There is only one buffer per path.
2818        let buffer_a_id = buffer_a_1.id();
2819        assert_eq!(buffer_a_2.id(), buffer_a_id);
2820
2821        // Open the same path again while it is still open.
2822        drop(buffer_a_1);
2823        let buffer_a_3 = project
2824            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
2825            .await
2826            .unwrap();
2827
2828        // There's still only one buffer per path.
2829        assert_eq!(buffer_a_3.id(), buffer_a_id);
2830    }
2831
2832    #[gpui::test]
2833    async fn test_buffer_is_dirty(mut cx: gpui::TestAppContext) {
2834        use std::fs;
2835
2836        let dir = temp_tree(json!({
2837            "file1": "abc",
2838            "file2": "def",
2839            "file3": "ghi",
2840        }));
2841
2842        let project = build_project(Arc::new(RealFs), &mut cx);
2843        let (worktree, _) = project
2844            .update(&mut cx, |p, cx| {
2845                p.find_or_create_local_worktree(dir.path(), false, cx)
2846            })
2847            .await
2848            .unwrap();
2849        let worktree_id = worktree.read_with(&cx, |worktree, _| worktree.id());
2850
2851        worktree.flush_fs_events(&cx).await;
2852        worktree
2853            .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
2854            .await;
2855
2856        let buffer1 = project
2857            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
2858            .await
2859            .unwrap();
2860        let events = Rc::new(RefCell::new(Vec::new()));
2861
2862        // initially, the buffer isn't dirty.
2863        buffer1.update(&mut cx, |buffer, cx| {
2864            cx.subscribe(&buffer1, {
2865                let events = events.clone();
2866                move |_, _, event, _| events.borrow_mut().push(event.clone())
2867            })
2868            .detach();
2869
2870            assert!(!buffer.is_dirty());
2871            assert!(events.borrow().is_empty());
2872
2873            buffer.edit(vec![1..2], "", cx);
2874        });
2875
2876        // after the first edit, the buffer is dirty, and emits a dirtied event.
2877        buffer1.update(&mut cx, |buffer, cx| {
2878            assert!(buffer.text() == "ac");
2879            assert!(buffer.is_dirty());
2880            assert_eq!(
2881                *events.borrow(),
2882                &[language::Event::Edited, language::Event::Dirtied]
2883            );
2884            events.borrow_mut().clear();
2885            buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
2886        });
2887
2888        // after saving, the buffer is not dirty, and emits a saved event.
2889        buffer1.update(&mut cx, |buffer, cx| {
2890            assert!(!buffer.is_dirty());
2891            assert_eq!(*events.borrow(), &[language::Event::Saved]);
2892            events.borrow_mut().clear();
2893
2894            buffer.edit(vec![1..1], "B", cx);
2895            buffer.edit(vec![2..2], "D", cx);
2896        });
2897
2898        // after editing again, the buffer is dirty, and emits another dirty event.
2899        buffer1.update(&mut cx, |buffer, cx| {
2900            assert!(buffer.text() == "aBDc");
2901            assert!(buffer.is_dirty());
2902            assert_eq!(
2903                *events.borrow(),
2904                &[
2905                    language::Event::Edited,
2906                    language::Event::Dirtied,
2907                    language::Event::Edited,
2908                ],
2909            );
2910            events.borrow_mut().clear();
2911
2912            // TODO - currently, after restoring the buffer to its
2913            // previously-saved state, the is still considered dirty.
2914            buffer.edit([1..3], "", cx);
2915            assert!(buffer.text() == "ac");
2916            assert!(buffer.is_dirty());
2917        });
2918
2919        assert_eq!(*events.borrow(), &[language::Event::Edited]);
2920
2921        // When a file is deleted, the buffer is considered dirty.
2922        let events = Rc::new(RefCell::new(Vec::new()));
2923        let buffer2 = project
2924            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file2"), cx))
2925            .await
2926            .unwrap();
2927        buffer2.update(&mut cx, |_, cx| {
2928            cx.subscribe(&buffer2, {
2929                let events = events.clone();
2930                move |_, _, event, _| events.borrow_mut().push(event.clone())
2931            })
2932            .detach();
2933        });
2934
2935        fs::remove_file(dir.path().join("file2")).unwrap();
2936        buffer2.condition(&cx, |b, _| b.is_dirty()).await;
2937        assert_eq!(
2938            *events.borrow(),
2939            &[language::Event::Dirtied, language::Event::FileHandleChanged]
2940        );
2941
2942        // When a file is already dirty when deleted, we don't emit a Dirtied event.
2943        let events = Rc::new(RefCell::new(Vec::new()));
2944        let buffer3 = project
2945            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file3"), cx))
2946            .await
2947            .unwrap();
2948        buffer3.update(&mut cx, |_, cx| {
2949            cx.subscribe(&buffer3, {
2950                let events = events.clone();
2951                move |_, _, event, _| events.borrow_mut().push(event.clone())
2952            })
2953            .detach();
2954        });
2955
2956        worktree.flush_fs_events(&cx).await;
2957        buffer3.update(&mut cx, |buffer, cx| {
2958            buffer.edit(Some(0..0), "x", cx);
2959        });
2960        events.borrow_mut().clear();
2961        fs::remove_file(dir.path().join("file3")).unwrap();
2962        buffer3
2963            .condition(&cx, |_, _| !events.borrow().is_empty())
2964            .await;
2965        assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
2966        cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
2967    }
2968
2969    #[gpui::test]
2970    async fn test_buffer_file_changes_on_disk(mut cx: gpui::TestAppContext) {
2971        use std::fs;
2972
2973        let initial_contents = "aaa\nbbbbb\nc\n";
2974        let dir = temp_tree(json!({ "the-file": initial_contents }));
2975
2976        let project = build_project(Arc::new(RealFs), &mut cx);
2977        let (worktree, _) = project
2978            .update(&mut cx, |p, cx| {
2979                p.find_or_create_local_worktree(dir.path(), false, cx)
2980            })
2981            .await
2982            .unwrap();
2983        let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
2984
2985        worktree
2986            .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
2987            .await;
2988
2989        let abs_path = dir.path().join("the-file");
2990        let buffer = project
2991            .update(&mut cx, |p, cx| {
2992                p.open_buffer((worktree_id, "the-file"), cx)
2993            })
2994            .await
2995            .unwrap();
2996
2997        // TODO
2998        // Add a cursor on each row.
2999        // let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
3000        //     assert!(!buffer.is_dirty());
3001        //     buffer.add_selection_set(
3002        //         &(0..3)
3003        //             .map(|row| Selection {
3004        //                 id: row as usize,
3005        //                 start: Point::new(row, 1),
3006        //                 end: Point::new(row, 1),
3007        //                 reversed: false,
3008        //                 goal: SelectionGoal::None,
3009        //             })
3010        //             .collect::<Vec<_>>(),
3011        //         cx,
3012        //     )
3013        // });
3014
3015        // Change the file on disk, adding two new lines of text, and removing
3016        // one line.
3017        buffer.read_with(&cx, |buffer, _| {
3018            assert!(!buffer.is_dirty());
3019            assert!(!buffer.has_conflict());
3020        });
3021        let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
3022        fs::write(&abs_path, new_contents).unwrap();
3023
3024        // Because the buffer was not modified, it is reloaded from disk. Its
3025        // contents are edited according to the diff between the old and new
3026        // file contents.
3027        buffer
3028            .condition(&cx, |buffer, _| buffer.text() == new_contents)
3029            .await;
3030
3031        buffer.update(&mut cx, |buffer, _| {
3032            assert_eq!(buffer.text(), new_contents);
3033            assert!(!buffer.is_dirty());
3034            assert!(!buffer.has_conflict());
3035
3036            // TODO
3037            // let cursor_positions = buffer
3038            //     .selection_set(selection_set_id)
3039            //     .unwrap()
3040            //     .selections::<Point>(&*buffer)
3041            //     .map(|selection| {
3042            //         assert_eq!(selection.start, selection.end);
3043            //         selection.start
3044            //     })
3045            //     .collect::<Vec<_>>();
3046            // assert_eq!(
3047            //     cursor_positions,
3048            //     [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
3049            // );
3050        });
3051
3052        // Modify the buffer
3053        buffer.update(&mut cx, |buffer, cx| {
3054            buffer.edit(vec![0..0], " ", cx);
3055            assert!(buffer.is_dirty());
3056            assert!(!buffer.has_conflict());
3057        });
3058
3059        // Change the file on disk again, adding blank lines to the beginning.
3060        fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
3061
3062        // Because the buffer is modified, it doesn't reload from disk, but is
3063        // marked as having a conflict.
3064        buffer
3065            .condition(&cx, |buffer, _| buffer.has_conflict())
3066            .await;
3067    }
3068
3069    #[gpui::test]
3070    async fn test_grouped_diagnostics(mut cx: gpui::TestAppContext) {
3071        let fs = Arc::new(FakeFs::new(cx.background()));
3072        fs.insert_tree(
3073            "/the-dir",
3074            json!({
3075                "a.rs": "
3076                    fn foo(mut v: Vec<usize>) {
3077                        for x in &v {
3078                            v.push(1);
3079                        }
3080                    }
3081                "
3082                .unindent(),
3083            }),
3084        )
3085        .await;
3086
3087        let project = build_project(fs.clone(), &mut cx);
3088        let (worktree, _) = project
3089            .update(&mut cx, |p, cx| {
3090                p.find_or_create_local_worktree("/the-dir", false, cx)
3091            })
3092            .await
3093            .unwrap();
3094        let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
3095
3096        let buffer = project
3097            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3098            .await
3099            .unwrap();
3100
3101        let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
3102        let message = lsp::PublishDiagnosticsParams {
3103            uri: buffer_uri.clone(),
3104            diagnostics: vec![
3105                lsp::Diagnostic {
3106                    range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3107                    severity: Some(DiagnosticSeverity::WARNING),
3108                    message: "error 1".to_string(),
3109                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3110                        location: lsp::Location {
3111                            uri: buffer_uri.clone(),
3112                            range: lsp::Range::new(
3113                                lsp::Position::new(1, 8),
3114                                lsp::Position::new(1, 9),
3115                            ),
3116                        },
3117                        message: "error 1 hint 1".to_string(),
3118                    }]),
3119                    ..Default::default()
3120                },
3121                lsp::Diagnostic {
3122                    range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3123                    severity: Some(DiagnosticSeverity::HINT),
3124                    message: "error 1 hint 1".to_string(),
3125                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3126                        location: lsp::Location {
3127                            uri: buffer_uri.clone(),
3128                            range: lsp::Range::new(
3129                                lsp::Position::new(1, 8),
3130                                lsp::Position::new(1, 9),
3131                            ),
3132                        },
3133                        message: "original diagnostic".to_string(),
3134                    }]),
3135                    ..Default::default()
3136                },
3137                lsp::Diagnostic {
3138                    range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
3139                    severity: Some(DiagnosticSeverity::ERROR),
3140                    message: "error 2".to_string(),
3141                    related_information: Some(vec![
3142                        lsp::DiagnosticRelatedInformation {
3143                            location: lsp::Location {
3144                                uri: buffer_uri.clone(),
3145                                range: lsp::Range::new(
3146                                    lsp::Position::new(1, 13),
3147                                    lsp::Position::new(1, 15),
3148                                ),
3149                            },
3150                            message: "error 2 hint 1".to_string(),
3151                        },
3152                        lsp::DiagnosticRelatedInformation {
3153                            location: lsp::Location {
3154                                uri: buffer_uri.clone(),
3155                                range: lsp::Range::new(
3156                                    lsp::Position::new(1, 13),
3157                                    lsp::Position::new(1, 15),
3158                                ),
3159                            },
3160                            message: "error 2 hint 2".to_string(),
3161                        },
3162                    ]),
3163                    ..Default::default()
3164                },
3165                lsp::Diagnostic {
3166                    range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
3167                    severity: Some(DiagnosticSeverity::HINT),
3168                    message: "error 2 hint 1".to_string(),
3169                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3170                        location: lsp::Location {
3171                            uri: buffer_uri.clone(),
3172                            range: lsp::Range::new(
3173                                lsp::Position::new(2, 8),
3174                                lsp::Position::new(2, 17),
3175                            ),
3176                        },
3177                        message: "original diagnostic".to_string(),
3178                    }]),
3179                    ..Default::default()
3180                },
3181                lsp::Diagnostic {
3182                    range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
3183                    severity: Some(DiagnosticSeverity::HINT),
3184                    message: "error 2 hint 2".to_string(),
3185                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3186                        location: lsp::Location {
3187                            uri: buffer_uri.clone(),
3188                            range: lsp::Range::new(
3189                                lsp::Position::new(2, 8),
3190                                lsp::Position::new(2, 17),
3191                            ),
3192                        },
3193                        message: "original diagnostic".to_string(),
3194                    }]),
3195                    ..Default::default()
3196                },
3197            ],
3198            version: None,
3199        };
3200
3201        project
3202            .update(&mut cx, |p, cx| {
3203                p.update_diagnostics(message, &Default::default(), cx)
3204            })
3205            .unwrap();
3206        let buffer = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3207
3208        assert_eq!(
3209            buffer
3210                .diagnostics_in_range::<_, Point>(0..buffer.len())
3211                .collect::<Vec<_>>(),
3212            &[
3213                DiagnosticEntry {
3214                    range: Point::new(1, 8)..Point::new(1, 9),
3215                    diagnostic: Diagnostic {
3216                        severity: DiagnosticSeverity::WARNING,
3217                        message: "error 1".to_string(),
3218                        group_id: 0,
3219                        is_primary: true,
3220                        ..Default::default()
3221                    }
3222                },
3223                DiagnosticEntry {
3224                    range: Point::new(1, 8)..Point::new(1, 9),
3225                    diagnostic: Diagnostic {
3226                        severity: DiagnosticSeverity::HINT,
3227                        message: "error 1 hint 1".to_string(),
3228                        group_id: 0,
3229                        is_primary: false,
3230                        ..Default::default()
3231                    }
3232                },
3233                DiagnosticEntry {
3234                    range: Point::new(1, 13)..Point::new(1, 15),
3235                    diagnostic: Diagnostic {
3236                        severity: DiagnosticSeverity::HINT,
3237                        message: "error 2 hint 1".to_string(),
3238                        group_id: 1,
3239                        is_primary: false,
3240                        ..Default::default()
3241                    }
3242                },
3243                DiagnosticEntry {
3244                    range: Point::new(1, 13)..Point::new(1, 15),
3245                    diagnostic: Diagnostic {
3246                        severity: DiagnosticSeverity::HINT,
3247                        message: "error 2 hint 2".to_string(),
3248                        group_id: 1,
3249                        is_primary: false,
3250                        ..Default::default()
3251                    }
3252                },
3253                DiagnosticEntry {
3254                    range: Point::new(2, 8)..Point::new(2, 17),
3255                    diagnostic: Diagnostic {
3256                        severity: DiagnosticSeverity::ERROR,
3257                        message: "error 2".to_string(),
3258                        group_id: 1,
3259                        is_primary: true,
3260                        ..Default::default()
3261                    }
3262                }
3263            ]
3264        );
3265
3266        assert_eq!(
3267            buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
3268            &[
3269                DiagnosticEntry {
3270                    range: Point::new(1, 8)..Point::new(1, 9),
3271                    diagnostic: Diagnostic {
3272                        severity: DiagnosticSeverity::WARNING,
3273                        message: "error 1".to_string(),
3274                        group_id: 0,
3275                        is_primary: true,
3276                        ..Default::default()
3277                    }
3278                },
3279                DiagnosticEntry {
3280                    range: Point::new(1, 8)..Point::new(1, 9),
3281                    diagnostic: Diagnostic {
3282                        severity: DiagnosticSeverity::HINT,
3283                        message: "error 1 hint 1".to_string(),
3284                        group_id: 0,
3285                        is_primary: false,
3286                        ..Default::default()
3287                    }
3288                },
3289            ]
3290        );
3291        assert_eq!(
3292            buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
3293            &[
3294                DiagnosticEntry {
3295                    range: Point::new(1, 13)..Point::new(1, 15),
3296                    diagnostic: Diagnostic {
3297                        severity: DiagnosticSeverity::HINT,
3298                        message: "error 2 hint 1".to_string(),
3299                        group_id: 1,
3300                        is_primary: false,
3301                        ..Default::default()
3302                    }
3303                },
3304                DiagnosticEntry {
3305                    range: Point::new(1, 13)..Point::new(1, 15),
3306                    diagnostic: Diagnostic {
3307                        severity: DiagnosticSeverity::HINT,
3308                        message: "error 2 hint 2".to_string(),
3309                        group_id: 1,
3310                        is_primary: false,
3311                        ..Default::default()
3312                    }
3313                },
3314                DiagnosticEntry {
3315                    range: Point::new(2, 8)..Point::new(2, 17),
3316                    diagnostic: Diagnostic {
3317                        severity: DiagnosticSeverity::ERROR,
3318                        message: "error 2".to_string(),
3319                        group_id: 1,
3320                        is_primary: true,
3321                        ..Default::default()
3322                    }
3323                }
3324            ]
3325        );
3326    }
3327
3328    fn build_project(fs: Arc<dyn Fs>, cx: &mut TestAppContext) -> ModelHandle<Project> {
3329        let languages = Arc::new(LanguageRegistry::new());
3330        let http_client = FakeHttpClient::with_404_response();
3331        let client = client::Client::new(http_client.clone());
3332        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3333        cx.update(|cx| Project::local(client, user_store, languages, fs, cx))
3334    }
3335}