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