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