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 = cx.read(|cx| 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(Err(anyhow!(
1069                                "buffer {} does not have a language server",
1070                                buffer.remote_id()
1071                            )));
1072                        };
1073                    } else {
1074                        return Task::ready(Err(anyhow!("buffer does not have a language")));
1075                    }
1076
1077                    local_buffers.push((buffer_handle, buffer_abs_path, lang_server));
1078                } else {
1079                    remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
1080                }
1081            } else {
1082                return Task::ready(Err(anyhow!(
1083                    "buffer {} does not belong to any worktree",
1084                    buffer.remote_id()
1085                )));
1086            }
1087        }
1088
1089        let remote_buffers = self.remote_id().zip(remote_buffers);
1090        let client = self.client.clone();
1091
1092        cx.spawn(|this, mut cx| async move {
1093            let mut project_transaction = ProjectTransaction::default();
1094
1095            if let Some((project_id, remote_buffers)) = remote_buffers {
1096                let response = client
1097                    .request(proto::FormatBuffers {
1098                        project_id,
1099                        buffer_ids: remote_buffers
1100                            .iter()
1101                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
1102                            .collect(),
1103                    })
1104                    .await?
1105                    .transaction
1106                    .ok_or_else(|| anyhow!("missing transaction"))?;
1107                project_transaction = this
1108                    .update(&mut cx, |this, cx| {
1109                        this.deserialize_project_transaction(response, push_to_history, cx)
1110                    })
1111                    .await?;
1112            }
1113
1114            for (buffer, buffer_abs_path, lang_server) in local_buffers {
1115                let lsp_edits = lang_server
1116                    .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
1117                        text_document: lsp::TextDocumentIdentifier::new(
1118                            lsp::Url::from_file_path(&buffer_abs_path).unwrap(),
1119                        ),
1120                        options: Default::default(),
1121                        work_done_progress_params: Default::default(),
1122                    })
1123                    .await?;
1124
1125                if let Some(lsp_edits) = lsp_edits {
1126                    let edits = buffer
1127                        .update(&mut cx, |buffer, cx| {
1128                            buffer.edits_from_lsp(lsp_edits, None, cx)
1129                        })
1130                        .await?;
1131                    buffer.update(&mut cx, |buffer, cx| {
1132                        buffer.finalize_last_transaction();
1133                        buffer.start_transaction();
1134                        for (range, text) in edits {
1135                            buffer.edit([range], text, cx);
1136                        }
1137                        if buffer.end_transaction(cx).is_some() {
1138                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
1139                            if !push_to_history {
1140                                buffer.forget_transaction(transaction.id);
1141                            }
1142                            project_transaction.0.insert(cx.handle(), transaction);
1143                        }
1144                    });
1145                }
1146            }
1147
1148            Ok(project_transaction)
1149        })
1150    }
1151
1152    pub fn definition<T: ToPointUtf16>(
1153        &self,
1154        source_buffer_handle: &ModelHandle<Buffer>,
1155        position: T,
1156        cx: &mut ModelContext<Self>,
1157    ) -> Task<Result<Vec<Definition>>> {
1158        let source_buffer_handle = source_buffer_handle.clone();
1159        let source_buffer = source_buffer_handle.read(cx);
1160        let worktree;
1161        let buffer_abs_path;
1162        if let Some(file) = File::from_dyn(source_buffer.file()) {
1163            worktree = file.worktree.clone();
1164            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
1165        } else {
1166            return Task::ready(Err(anyhow!("buffer does not belong to any worktree")));
1167        };
1168
1169        let position = position.to_point_utf16(source_buffer);
1170
1171        if worktree.read(cx).as_local().is_some() {
1172            let buffer_abs_path = buffer_abs_path.unwrap();
1173            let lang_name;
1174            let lang_server;
1175            if let Some(lang) = source_buffer.language() {
1176                lang_name = lang.name().to_string();
1177                if let Some(server) = self
1178                    .language_servers
1179                    .get(&(worktree.read(cx).id(), lang_name.clone()))
1180                {
1181                    lang_server = server.clone();
1182                } else {
1183                    return Task::ready(Err(anyhow!("buffer does not have a language server")));
1184                };
1185            } else {
1186                return Task::ready(Err(anyhow!("buffer does not have a language")));
1187            }
1188
1189            cx.spawn(|this, mut cx| async move {
1190                let response = lang_server
1191                    .request::<lsp::request::GotoDefinition>(lsp::GotoDefinitionParams {
1192                        text_document_position_params: lsp::TextDocumentPositionParams {
1193                            text_document: lsp::TextDocumentIdentifier::new(
1194                                lsp::Url::from_file_path(&buffer_abs_path).unwrap(),
1195                            ),
1196                            position: lsp::Position::new(position.row, position.column),
1197                        },
1198                        work_done_progress_params: Default::default(),
1199                        partial_result_params: Default::default(),
1200                    })
1201                    .await?;
1202
1203                let mut definitions = Vec::new();
1204                if let Some(response) = response {
1205                    let mut unresolved_locations = Vec::new();
1206                    match response {
1207                        lsp::GotoDefinitionResponse::Scalar(loc) => {
1208                            unresolved_locations.push((loc.uri, loc.range));
1209                        }
1210                        lsp::GotoDefinitionResponse::Array(locs) => {
1211                            unresolved_locations.extend(locs.into_iter().map(|l| (l.uri, l.range)));
1212                        }
1213                        lsp::GotoDefinitionResponse::Link(links) => {
1214                            unresolved_locations.extend(
1215                                links
1216                                    .into_iter()
1217                                    .map(|l| (l.target_uri, l.target_selection_range)),
1218                            );
1219                        }
1220                    }
1221
1222                    for (target_uri, target_range) in unresolved_locations {
1223                        let target_buffer_handle = this
1224                            .update(&mut cx, |this, cx| {
1225                                this.open_local_buffer_from_lsp_path(
1226                                    target_uri,
1227                                    lang_name.clone(),
1228                                    lang_server.clone(),
1229                                    cx,
1230                                )
1231                            })
1232                            .await?;
1233
1234                        cx.read(|cx| {
1235                            let target_buffer = target_buffer_handle.read(cx);
1236                            let target_start = target_buffer
1237                                .clip_point_utf16(point_from_lsp(target_range.start), Bias::Left);
1238                            let target_end = target_buffer
1239                                .clip_point_utf16(point_from_lsp(target_range.end), Bias::Left);
1240                            definitions.push(Definition {
1241                                target_buffer: target_buffer_handle,
1242                                target_range: target_buffer.anchor_after(target_start)
1243                                    ..target_buffer.anchor_before(target_end),
1244                            });
1245                        });
1246                    }
1247                }
1248
1249                Ok(definitions)
1250            })
1251        } else if let Some(project_id) = self.remote_id() {
1252            let client = self.client.clone();
1253            let request = proto::GetDefinition {
1254                project_id,
1255                buffer_id: source_buffer.remote_id(),
1256                position: Some(serialize_anchor(&source_buffer.anchor_before(position))),
1257            };
1258            cx.spawn(|this, mut cx| async move {
1259                let response = client.request(request).await?;
1260                this.update(&mut cx, |this, cx| {
1261                    let mut definitions = Vec::new();
1262                    for definition in response.definitions {
1263                        let target_buffer = this.deserialize_buffer(
1264                            definition.buffer.ok_or_else(|| anyhow!("missing buffer"))?,
1265                            cx,
1266                        )?;
1267                        let target_start = definition
1268                            .target_start
1269                            .and_then(deserialize_anchor)
1270                            .ok_or_else(|| anyhow!("missing target start"))?;
1271                        let target_end = definition
1272                            .target_end
1273                            .and_then(deserialize_anchor)
1274                            .ok_or_else(|| anyhow!("missing target end"))?;
1275                        definitions.push(Definition {
1276                            target_buffer,
1277                            target_range: target_start..target_end,
1278                        })
1279                    }
1280
1281                    Ok(definitions)
1282                })
1283            })
1284        } else {
1285            Task::ready(Err(anyhow!("project does not have a remote id")))
1286        }
1287    }
1288
1289    pub fn completions<T: ToPointUtf16>(
1290        &self,
1291        source_buffer_handle: &ModelHandle<Buffer>,
1292        position: T,
1293        cx: &mut ModelContext<Self>,
1294    ) -> Task<Result<Vec<Completion>>> {
1295        let source_buffer_handle = source_buffer_handle.clone();
1296        let source_buffer = source_buffer_handle.read(cx);
1297        let buffer_id = source_buffer.remote_id();
1298        let language = source_buffer.language().cloned();
1299        let worktree;
1300        let buffer_abs_path;
1301        if let Some(file) = File::from_dyn(source_buffer.file()) {
1302            worktree = file.worktree.clone();
1303            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
1304        } else {
1305            return Task::ready(Err(anyhow!("buffer does not belong to any worktree")));
1306        };
1307
1308        let position = position.to_point_utf16(source_buffer);
1309        let anchor = source_buffer.anchor_after(position);
1310
1311        if worktree.read(cx).as_local().is_some() {
1312            let buffer_abs_path = buffer_abs_path.unwrap();
1313            let lang_server = if let Some(server) = source_buffer.language_server().cloned() {
1314                server
1315            } else {
1316                return Task::ready(Err(anyhow!("buffer does not have a language server")));
1317            };
1318
1319            cx.spawn(|_, cx| async move {
1320                let completions = lang_server
1321                .request::<lsp::request::Completion>(lsp::CompletionParams {
1322                    text_document_position: lsp::TextDocumentPositionParams::new(
1323                        lsp::TextDocumentIdentifier::new(
1324                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
1325                        ),
1326                        position.to_lsp_position(),
1327                    ),
1328                    context: Default::default(),
1329                    work_done_progress_params: Default::default(),
1330                    partial_result_params: Default::default(),
1331                })
1332                .await?;
1333
1334                let completions = if let Some(completions) = completions {
1335                    match completions {
1336                        lsp::CompletionResponse::Array(completions) => completions,
1337                        lsp::CompletionResponse::List(list) => list.items,
1338                    }
1339                } else {
1340                    Default::default()
1341                };
1342
1343                source_buffer_handle.read_with(&cx, |this, _| {
1344                    Ok(completions.into_iter().filter_map(|lsp_completion| {
1345                        let (old_range, new_text) = match lsp_completion.text_edit.as_ref()? {
1346                            lsp::CompletionTextEdit::Edit(edit) => (range_from_lsp(edit.range), edit.new_text.clone()),
1347                            lsp::CompletionTextEdit::InsertAndReplace(_) => {
1348                                log::info!("received an insert and replace completion but we don't yet support that");
1349                                return None
1350                            },
1351                        };
1352
1353                        let clipped_start = this.clip_point_utf16(old_range.start, Bias::Left);
1354                        let clipped_end = this.clip_point_utf16(old_range.end, Bias::Left) ;
1355                        if clipped_start == old_range.start && clipped_end == old_range.end {
1356                            Some(Completion {
1357                                old_range: this.anchor_before(old_range.start)..this.anchor_after(old_range.end),
1358                                new_text,
1359                                label: language.as_ref().and_then(|l| l.label_for_completion(&lsp_completion)).unwrap_or_else(|| CompletionLabel::plain(&lsp_completion)),
1360                                lsp_completion,
1361                            })
1362                        } else {
1363                            None
1364                        }
1365                    }).collect())
1366                })
1367
1368            })
1369        } else if let Some(project_id) = self.remote_id() {
1370            let rpc = self.client.clone();
1371            cx.foreground().spawn(async move {
1372                let response = rpc
1373                    .request(proto::GetCompletions {
1374                        project_id,
1375                        buffer_id,
1376                        position: Some(language::proto::serialize_anchor(&anchor)),
1377                    })
1378                    .await?;
1379                response
1380                    .completions
1381                    .into_iter()
1382                    .map(|completion| {
1383                        language::proto::deserialize_completion(completion, language.as_ref())
1384                    })
1385                    .collect()
1386            })
1387        } else {
1388            Task::ready(Err(anyhow!("project does not have a remote id")))
1389        }
1390    }
1391
1392    pub fn apply_additional_edits_for_completion(
1393        &self,
1394        buffer_handle: ModelHandle<Buffer>,
1395        completion: Completion,
1396        push_to_history: bool,
1397        cx: &mut ModelContext<Self>,
1398    ) -> Task<Result<Option<Transaction>>> {
1399        let buffer = buffer_handle.read(cx);
1400        let buffer_id = buffer.remote_id();
1401
1402        if self.is_local() {
1403            let lang_server = if let Some(language_server) = buffer.language_server() {
1404                language_server.clone()
1405            } else {
1406                return Task::ready(Ok(Default::default()));
1407            };
1408
1409            cx.spawn(|_, mut cx| async move {
1410                let resolved_completion = lang_server
1411                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
1412                    .await?;
1413                if let Some(additional_edits) = resolved_completion.additional_text_edits {
1414                    buffer_handle.update(&mut cx, |buffer, cx| {
1415                        buffer.finalize_last_transaction();
1416                        buffer.start_transaction();
1417                        buffer.apply_lsp_edits(additional_edits, None, cx).log_err();
1418                        let transaction = if buffer.end_transaction(cx).is_some() {
1419                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
1420                            if !push_to_history {
1421                                buffer.forget_transaction(transaction.id);
1422                            }
1423                            Some(transaction)
1424                        } else {
1425                            None
1426                        };
1427                        Ok(transaction)
1428                    })
1429                } else {
1430                    Ok(None)
1431                }
1432            })
1433        } else if let Some(project_id) = self.remote_id() {
1434            let client = self.client.clone();
1435            cx.spawn(|_, mut cx| async move {
1436                let response = client
1437                    .request(proto::ApplyCompletionAdditionalEdits {
1438                        project_id,
1439                        buffer_id,
1440                        completion: Some(language::proto::serialize_completion(&completion)),
1441                    })
1442                    .await?;
1443
1444                if let Some(transaction) = response.transaction {
1445                    let transaction = language::proto::deserialize_transaction(transaction)?;
1446                    buffer_handle
1447                        .update(&mut cx, |buffer, _| {
1448                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
1449                        })
1450                        .await;
1451                    if push_to_history {
1452                        buffer_handle.update(&mut cx, |buffer, _| {
1453                            buffer.push_transaction(transaction.clone(), Instant::now());
1454                        });
1455                    }
1456                    Ok(Some(transaction))
1457                } else {
1458                    Ok(None)
1459                }
1460            })
1461        } else {
1462            Task::ready(Err(anyhow!("project does not have a remote id")))
1463        }
1464    }
1465
1466    pub fn code_actions<T: ToPointUtf16>(
1467        &self,
1468        source_buffer_handle: &ModelHandle<Buffer>,
1469        position: T,
1470        cx: &mut ModelContext<Self>,
1471    ) -> Task<Result<Vec<CodeAction>>> {
1472        let source_buffer_handle = source_buffer_handle.clone();
1473        let source_buffer = source_buffer_handle.read(cx);
1474        let buffer_id = source_buffer.remote_id();
1475        let worktree;
1476        let buffer_abs_path;
1477        if let Some(file) = File::from_dyn(source_buffer.file()) {
1478            worktree = file.worktree.clone();
1479            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
1480        } else {
1481            return Task::ready(Err(anyhow!("buffer does not belong to any worktree")));
1482        };
1483
1484        let position = position.to_point_utf16(source_buffer);
1485        let anchor = source_buffer.anchor_after(position);
1486
1487        if worktree.read(cx).as_local().is_some() {
1488            let buffer_abs_path = buffer_abs_path.unwrap();
1489            let lang_name;
1490            let lang_server;
1491            if let Some(lang) = source_buffer.language() {
1492                lang_name = lang.name().to_string();
1493                if let Some(server) = self
1494                    .language_servers
1495                    .get(&(worktree.read(cx).id(), lang_name.clone()))
1496                {
1497                    lang_server = server.clone();
1498                } else {
1499                    return Task::ready(Err(anyhow!("buffer does not have a language server")));
1500                };
1501            } else {
1502                return Task::ready(Err(anyhow!("buffer does not have a language")));
1503            }
1504
1505            cx.foreground().spawn(async move {
1506                let actions = lang_server
1507                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
1508                        text_document: lsp::TextDocumentIdentifier::new(
1509                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
1510                        ),
1511                        range: lsp::Range::new(
1512                            position.to_lsp_position(),
1513                            position.to_lsp_position(),
1514                        ),
1515                        work_done_progress_params: Default::default(),
1516                        partial_result_params: Default::default(),
1517                        context: lsp::CodeActionContext {
1518                            diagnostics: Default::default(),
1519                            only: Some(vec![
1520                                lsp::CodeActionKind::QUICKFIX,
1521                                lsp::CodeActionKind::REFACTOR,
1522                                lsp::CodeActionKind::REFACTOR_EXTRACT,
1523                            ]),
1524                        },
1525                    })
1526                    .await?
1527                    .unwrap_or_default()
1528                    .into_iter()
1529                    .filter_map(|entry| {
1530                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
1531                            Some(CodeAction {
1532                                position: anchor.clone(),
1533                                lsp_action,
1534                            })
1535                        } else {
1536                            None
1537                        }
1538                    })
1539                    .collect();
1540                Ok(actions)
1541            })
1542        } else if let Some(project_id) = self.remote_id() {
1543            let rpc = self.client.clone();
1544            cx.foreground().spawn(async move {
1545                let response = rpc
1546                    .request(proto::GetCodeActions {
1547                        project_id,
1548                        buffer_id,
1549                        position: Some(language::proto::serialize_anchor(&anchor)),
1550                    })
1551                    .await?;
1552                response
1553                    .actions
1554                    .into_iter()
1555                    .map(language::proto::deserialize_code_action)
1556                    .collect()
1557            })
1558        } else {
1559            Task::ready(Err(anyhow!("project does not have a remote id")))
1560        }
1561    }
1562
1563    pub fn apply_code_action(
1564        &self,
1565        buffer_handle: ModelHandle<Buffer>,
1566        mut action: CodeAction,
1567        push_to_history: bool,
1568        cx: &mut ModelContext<Self>,
1569    ) -> Task<Result<ProjectTransaction>> {
1570        if self.is_local() {
1571            let buffer = buffer_handle.read(cx);
1572            let lang_name = if let Some(lang) = buffer.language() {
1573                lang.name().to_string()
1574            } else {
1575                return Task::ready(Ok(Default::default()));
1576            };
1577            let lang_server = if let Some(language_server) = buffer.language_server() {
1578                language_server.clone()
1579            } else {
1580                return Task::ready(Ok(Default::default()));
1581            };
1582            let position = action.position.to_point_utf16(buffer).to_lsp_position();
1583            let fs = self.fs.clone();
1584
1585            cx.spawn(|this, mut cx| async move {
1586                if let Some(range) = action
1587                    .lsp_action
1588                    .data
1589                    .as_mut()
1590                    .and_then(|d| d.get_mut("codeActionParams"))
1591                    .and_then(|d| d.get_mut("range"))
1592                {
1593                    *range = serde_json::to_value(&lsp::Range::new(position, position)).unwrap();
1594                    action.lsp_action = lang_server
1595                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
1596                        .await?;
1597                } else {
1598                    let actions = this
1599                        .update(&mut cx, |this, cx| {
1600                            this.code_actions(&buffer_handle, action.position.clone(), cx)
1601                        })
1602                        .await?;
1603                    action.lsp_action = actions
1604                        .into_iter()
1605                        .find(|a| a.lsp_action.title == action.lsp_action.title)
1606                        .ok_or_else(|| anyhow!("code action is outdated"))?
1607                        .lsp_action;
1608                }
1609
1610                let mut operations = Vec::new();
1611                if let Some(edit) = action.lsp_action.edit {
1612                    if let Some(document_changes) = edit.document_changes {
1613                        match document_changes {
1614                            lsp::DocumentChanges::Edits(edits) => operations
1615                                .extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit)),
1616                            lsp::DocumentChanges::Operations(ops) => operations = ops,
1617                        }
1618                    } else if let Some(changes) = edit.changes {
1619                        operations.extend(changes.into_iter().map(|(uri, edits)| {
1620                            lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
1621                                text_document: lsp::OptionalVersionedTextDocumentIdentifier {
1622                                    uri,
1623                                    version: None,
1624                                },
1625                                edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
1626                            })
1627                        }));
1628                    }
1629                }
1630
1631                let mut project_transaction = ProjectTransaction::default();
1632                for operation in operations {
1633                    match operation {
1634                        lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
1635                            let abs_path = op
1636                                .uri
1637                                .to_file_path()
1638                                .map_err(|_| anyhow!("can't convert URI to path"))?;
1639
1640                            if let Some(parent_path) = abs_path.parent() {
1641                                fs.create_dir(parent_path).await?;
1642                            }
1643                            if abs_path.ends_with("/") {
1644                                fs.create_dir(&abs_path).await?;
1645                            } else {
1646                                fs.create_file(
1647                                    &abs_path,
1648                                    op.options.map(Into::into).unwrap_or_default(),
1649                                )
1650                                .await?;
1651                            }
1652                        }
1653                        lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
1654                            let source_abs_path = op
1655                                .old_uri
1656                                .to_file_path()
1657                                .map_err(|_| anyhow!("can't convert URI to path"))?;
1658                            let target_abs_path = op
1659                                .new_uri
1660                                .to_file_path()
1661                                .map_err(|_| anyhow!("can't convert URI to path"))?;
1662                            fs.rename(
1663                                &source_abs_path,
1664                                &target_abs_path,
1665                                op.options.map(Into::into).unwrap_or_default(),
1666                            )
1667                            .await?;
1668                        }
1669                        lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
1670                            let abs_path = op
1671                                .uri
1672                                .to_file_path()
1673                                .map_err(|_| anyhow!("can't convert URI to path"))?;
1674                            let options = op.options.map(Into::into).unwrap_or_default();
1675                            if abs_path.ends_with("/") {
1676                                fs.remove_dir(&abs_path, options).await?;
1677                            } else {
1678                                fs.remove_file(&abs_path, options).await?;
1679                            }
1680                        }
1681                        lsp::DocumentChangeOperation::Edit(op) => {
1682                            let buffer_to_edit = this
1683                                .update(&mut cx, |this, cx| {
1684                                    this.open_local_buffer_from_lsp_path(
1685                                        op.text_document.uri,
1686                                        lang_name.clone(),
1687                                        lang_server.clone(),
1688                                        cx,
1689                                    )
1690                                })
1691                                .await?;
1692
1693                            let edits = buffer_to_edit
1694                                .update(&mut cx, |buffer, cx| {
1695                                    let edits = op.edits.into_iter().map(|edit| match edit {
1696                                        lsp::OneOf::Left(edit) => edit,
1697                                        lsp::OneOf::Right(edit) => edit.text_edit,
1698                                    });
1699                                    buffer.edits_from_lsp(edits, op.text_document.version, cx)
1700                                })
1701                                .await?;
1702
1703                            let transaction = buffer_to_edit.update(&mut cx, |buffer, cx| {
1704                                buffer.finalize_last_transaction();
1705                                buffer.start_transaction();
1706                                for (range, text) in edits {
1707                                    buffer.edit([range], text, cx);
1708                                }
1709                                let transaction = if buffer.end_transaction(cx).is_some() {
1710                                    let transaction =
1711                                        buffer.finalize_last_transaction().unwrap().clone();
1712                                    if !push_to_history {
1713                                        buffer.forget_transaction(transaction.id);
1714                                    }
1715                                    Some(transaction)
1716                                } else {
1717                                    None
1718                                };
1719
1720                                transaction
1721                            });
1722                            if let Some(transaction) = transaction {
1723                                project_transaction.0.insert(buffer_to_edit, transaction);
1724                            }
1725                        }
1726                    }
1727                }
1728
1729                Ok(project_transaction)
1730            })
1731        } else if let Some(project_id) = self.remote_id() {
1732            let client = self.client.clone();
1733            let request = proto::ApplyCodeAction {
1734                project_id,
1735                buffer_id: buffer_handle.read(cx).remote_id(),
1736                action: Some(language::proto::serialize_code_action(&action)),
1737            };
1738            cx.spawn(|this, mut cx| async move {
1739                let response = client
1740                    .request(request)
1741                    .await?
1742                    .transaction
1743                    .ok_or_else(|| anyhow!("missing transaction"))?;
1744                this.update(&mut cx, |this, cx| {
1745                    this.deserialize_project_transaction(response, push_to_history, cx)
1746                })
1747                .await
1748            })
1749        } else {
1750            Task::ready(Err(anyhow!("project does not have a remote id")))
1751        }
1752    }
1753
1754    pub fn find_or_create_local_worktree(
1755        &self,
1756        abs_path: impl AsRef<Path>,
1757        weak: bool,
1758        cx: &mut ModelContext<Self>,
1759    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
1760        let abs_path = abs_path.as_ref();
1761        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
1762            Task::ready(Ok((tree.clone(), relative_path.into())))
1763        } else {
1764            let worktree = self.create_local_worktree(abs_path, weak, cx);
1765            cx.foreground()
1766                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
1767        }
1768    }
1769
1770    fn find_local_worktree(
1771        &self,
1772        abs_path: &Path,
1773        cx: &AppContext,
1774    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
1775        for tree in self.worktrees(cx) {
1776            if let Some(relative_path) = tree
1777                .read(cx)
1778                .as_local()
1779                .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
1780            {
1781                return Some((tree.clone(), relative_path.into()));
1782            }
1783        }
1784        None
1785    }
1786
1787    pub fn is_shared(&self) -> bool {
1788        match &self.client_state {
1789            ProjectClientState::Local { is_shared, .. } => *is_shared,
1790            ProjectClientState::Remote { .. } => false,
1791        }
1792    }
1793
1794    fn create_local_worktree(
1795        &self,
1796        abs_path: impl AsRef<Path>,
1797        weak: bool,
1798        cx: &mut ModelContext<Self>,
1799    ) -> Task<Result<ModelHandle<Worktree>>> {
1800        let fs = self.fs.clone();
1801        let client = self.client.clone();
1802        let path = Arc::from(abs_path.as_ref());
1803        cx.spawn(|project, mut cx| async move {
1804            let worktree = Worktree::local(client.clone(), path, weak, fs, &mut cx).await?;
1805
1806            let (remote_project_id, is_shared) = project.update(&mut cx, |project, cx| {
1807                project.add_worktree(&worktree, cx);
1808                (project.remote_id(), project.is_shared())
1809            });
1810
1811            if let Some(project_id) = remote_project_id {
1812                worktree
1813                    .update(&mut cx, |worktree, cx| {
1814                        worktree.as_local_mut().unwrap().register(project_id, cx)
1815                    })
1816                    .await?;
1817                if is_shared {
1818                    worktree
1819                        .update(&mut cx, |worktree, cx| {
1820                            worktree.as_local_mut().unwrap().share(project_id, cx)
1821                        })
1822                        .await?;
1823                }
1824            }
1825
1826            Ok(worktree)
1827        })
1828    }
1829
1830    pub fn remove_worktree(&mut self, id: WorktreeId, cx: &mut ModelContext<Self>) {
1831        self.worktrees.retain(|worktree| {
1832            worktree
1833                .upgrade(cx)
1834                .map_or(false, |w| w.read(cx).id() != id)
1835        });
1836        cx.notify();
1837    }
1838
1839    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
1840        cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
1841        if worktree.read(cx).is_local() {
1842            cx.subscribe(&worktree, |this, worktree, _, cx| {
1843                this.update_local_worktree_buffers(worktree, cx);
1844            })
1845            .detach();
1846        }
1847
1848        let push_weak_handle = {
1849            let worktree = worktree.read(cx);
1850            worktree.is_local() && worktree.is_weak()
1851        };
1852        if push_weak_handle {
1853            cx.observe_release(&worktree, |this, cx| {
1854                this.worktrees
1855                    .retain(|worktree| worktree.upgrade(cx).is_some());
1856                cx.notify();
1857            })
1858            .detach();
1859            self.worktrees
1860                .push(WorktreeHandle::Weak(worktree.downgrade()));
1861        } else {
1862            self.worktrees
1863                .push(WorktreeHandle::Strong(worktree.clone()));
1864        }
1865        cx.notify();
1866    }
1867
1868    fn update_local_worktree_buffers(
1869        &mut self,
1870        worktree_handle: ModelHandle<Worktree>,
1871        cx: &mut ModelContext<Self>,
1872    ) {
1873        let snapshot = worktree_handle.read(cx).snapshot();
1874        let mut buffers_to_delete = Vec::new();
1875        for (buffer_id, buffer) in &self.open_buffers {
1876            if let Some(buffer) = buffer.upgrade(cx) {
1877                buffer.update(cx, |buffer, cx| {
1878                    if let Some(old_file) = File::from_dyn(buffer.file()) {
1879                        if old_file.worktree != worktree_handle {
1880                            return;
1881                        }
1882
1883                        let new_file = if let Some(entry) = old_file
1884                            .entry_id
1885                            .and_then(|entry_id| snapshot.entry_for_id(entry_id))
1886                        {
1887                            File {
1888                                is_local: true,
1889                                entry_id: Some(entry.id),
1890                                mtime: entry.mtime,
1891                                path: entry.path.clone(),
1892                                worktree: worktree_handle.clone(),
1893                            }
1894                        } else if let Some(entry) =
1895                            snapshot.entry_for_path(old_file.path().as_ref())
1896                        {
1897                            File {
1898                                is_local: true,
1899                                entry_id: Some(entry.id),
1900                                mtime: entry.mtime,
1901                                path: entry.path.clone(),
1902                                worktree: worktree_handle.clone(),
1903                            }
1904                        } else {
1905                            File {
1906                                is_local: true,
1907                                entry_id: None,
1908                                path: old_file.path().clone(),
1909                                mtime: old_file.mtime(),
1910                                worktree: worktree_handle.clone(),
1911                            }
1912                        };
1913
1914                        if let Some(project_id) = self.remote_id() {
1915                            self.client
1916                                .send(proto::UpdateBufferFile {
1917                                    project_id,
1918                                    buffer_id: *buffer_id as u64,
1919                                    file: Some(new_file.to_proto()),
1920                                })
1921                                .log_err();
1922                        }
1923                        buffer.file_updated(Box::new(new_file), cx).detach();
1924                    }
1925                });
1926            } else {
1927                buffers_to_delete.push(*buffer_id);
1928            }
1929        }
1930
1931        for buffer_id in buffers_to_delete {
1932            self.open_buffers.remove(&buffer_id);
1933        }
1934    }
1935
1936    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
1937        let new_active_entry = entry.and_then(|project_path| {
1938            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
1939            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
1940            Some(ProjectEntry {
1941                worktree_id: project_path.worktree_id,
1942                entry_id: entry.id,
1943            })
1944        });
1945        if new_active_entry != self.active_entry {
1946            self.active_entry = new_active_entry;
1947            cx.emit(Event::ActiveEntryChanged(new_active_entry));
1948        }
1949    }
1950
1951    pub fn is_running_disk_based_diagnostics(&self) -> bool {
1952        self.language_servers_with_diagnostics_running > 0
1953    }
1954
1955    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
1956        let mut summary = DiagnosticSummary::default();
1957        for (_, path_summary) in self.diagnostic_summaries(cx) {
1958            summary.error_count += path_summary.error_count;
1959            summary.warning_count += path_summary.warning_count;
1960            summary.info_count += path_summary.info_count;
1961            summary.hint_count += path_summary.hint_count;
1962        }
1963        summary
1964    }
1965
1966    pub fn diagnostic_summaries<'a>(
1967        &'a self,
1968        cx: &'a AppContext,
1969    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
1970        self.worktrees(cx).flat_map(move |worktree| {
1971            let worktree = worktree.read(cx);
1972            let worktree_id = worktree.id();
1973            worktree
1974                .diagnostic_summaries()
1975                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
1976        })
1977    }
1978
1979    pub fn disk_based_diagnostics_started(&mut self, cx: &mut ModelContext<Self>) {
1980        self.language_servers_with_diagnostics_running += 1;
1981        if self.language_servers_with_diagnostics_running == 1 {
1982            cx.emit(Event::DiskBasedDiagnosticsStarted);
1983        }
1984    }
1985
1986    pub fn disk_based_diagnostics_finished(&mut self, cx: &mut ModelContext<Self>) {
1987        cx.emit(Event::DiskBasedDiagnosticsUpdated);
1988        self.language_servers_with_diagnostics_running -= 1;
1989        if self.language_servers_with_diagnostics_running == 0 {
1990            cx.emit(Event::DiskBasedDiagnosticsFinished);
1991        }
1992    }
1993
1994    pub fn active_entry(&self) -> Option<ProjectEntry> {
1995        self.active_entry
1996    }
1997
1998    // RPC message handlers
1999
2000    fn handle_unshare_project(
2001        &mut self,
2002        _: TypedEnvelope<proto::UnshareProject>,
2003        _: Arc<Client>,
2004        cx: &mut ModelContext<Self>,
2005    ) -> Result<()> {
2006        if let ProjectClientState::Remote {
2007            sharing_has_stopped,
2008            ..
2009        } = &mut self.client_state
2010        {
2011            *sharing_has_stopped = true;
2012            self.collaborators.clear();
2013            cx.notify();
2014            Ok(())
2015        } else {
2016            unreachable!()
2017        }
2018    }
2019
2020    fn handle_add_collaborator(
2021        &mut self,
2022        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
2023        _: Arc<Client>,
2024        cx: &mut ModelContext<Self>,
2025    ) -> Result<()> {
2026        let user_store = self.user_store.clone();
2027        let collaborator = envelope
2028            .payload
2029            .collaborator
2030            .take()
2031            .ok_or_else(|| anyhow!("empty collaborator"))?;
2032
2033        cx.spawn(|this, mut cx| {
2034            async move {
2035                let collaborator =
2036                    Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
2037                this.update(&mut cx, |this, cx| {
2038                    this.collaborators
2039                        .insert(collaborator.peer_id, collaborator);
2040                    cx.notify();
2041                });
2042                Ok(())
2043            }
2044            .log_err()
2045        })
2046        .detach();
2047
2048        Ok(())
2049    }
2050
2051    fn handle_remove_collaborator(
2052        &mut self,
2053        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
2054        _: Arc<Client>,
2055        cx: &mut ModelContext<Self>,
2056    ) -> Result<()> {
2057        let peer_id = PeerId(envelope.payload.peer_id);
2058        let replica_id = self
2059            .collaborators
2060            .remove(&peer_id)
2061            .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
2062            .replica_id;
2063        self.shared_buffers.remove(&peer_id);
2064        for (_, buffer) in &self.open_buffers {
2065            if let Some(buffer) = buffer.upgrade(cx) {
2066                buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
2067            }
2068        }
2069        cx.notify();
2070        Ok(())
2071    }
2072
2073    fn handle_share_worktree(
2074        &mut self,
2075        envelope: TypedEnvelope<proto::ShareWorktree>,
2076        client: Arc<Client>,
2077        cx: &mut ModelContext<Self>,
2078    ) -> Result<()> {
2079        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
2080        let replica_id = self.replica_id();
2081        let worktree = envelope
2082            .payload
2083            .worktree
2084            .ok_or_else(|| anyhow!("invalid worktree"))?;
2085        let (worktree, load_task) = Worktree::remote(remote_id, replica_id, worktree, client, cx);
2086        self.add_worktree(&worktree, cx);
2087        load_task.detach();
2088        Ok(())
2089    }
2090
2091    fn handle_unregister_worktree(
2092        &mut self,
2093        envelope: TypedEnvelope<proto::UnregisterWorktree>,
2094        _: Arc<Client>,
2095        cx: &mut ModelContext<Self>,
2096    ) -> Result<()> {
2097        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2098        self.remove_worktree(worktree_id, cx);
2099        Ok(())
2100    }
2101
2102    fn handle_update_worktree(
2103        &mut self,
2104        envelope: TypedEnvelope<proto::UpdateWorktree>,
2105        _: Arc<Client>,
2106        cx: &mut ModelContext<Self>,
2107    ) -> Result<()> {
2108        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2109        if let Some(worktree) = self.worktree_for_id(worktree_id, cx) {
2110            worktree.update(cx, |worktree, cx| {
2111                let worktree = worktree.as_remote_mut().unwrap();
2112                worktree.update_from_remote(envelope, cx)
2113            })?;
2114        }
2115        Ok(())
2116    }
2117
2118    fn handle_update_diagnostic_summary(
2119        &mut self,
2120        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
2121        _: Arc<Client>,
2122        cx: &mut ModelContext<Self>,
2123    ) -> Result<()> {
2124        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2125        if let Some(worktree) = self.worktree_for_id(worktree_id, cx) {
2126            if let Some(summary) = envelope.payload.summary {
2127                let project_path = ProjectPath {
2128                    worktree_id,
2129                    path: Path::new(&summary.path).into(),
2130                };
2131                worktree.update(cx, |worktree, _| {
2132                    worktree
2133                        .as_remote_mut()
2134                        .unwrap()
2135                        .update_diagnostic_summary(project_path.path.clone(), &summary);
2136                });
2137                cx.emit(Event::DiagnosticsUpdated(project_path));
2138            }
2139        }
2140        Ok(())
2141    }
2142
2143    fn handle_disk_based_diagnostics_updating(
2144        &mut self,
2145        _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
2146        _: Arc<Client>,
2147        cx: &mut ModelContext<Self>,
2148    ) -> Result<()> {
2149        self.disk_based_diagnostics_started(cx);
2150        Ok(())
2151    }
2152
2153    fn handle_disk_based_diagnostics_updated(
2154        &mut self,
2155        _: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
2156        _: Arc<Client>,
2157        cx: &mut ModelContext<Self>,
2158    ) -> Result<()> {
2159        self.disk_based_diagnostics_finished(cx);
2160        Ok(())
2161    }
2162
2163    pub fn handle_update_buffer(
2164        &mut self,
2165        envelope: TypedEnvelope<proto::UpdateBuffer>,
2166        _: Arc<Client>,
2167        cx: &mut ModelContext<Self>,
2168    ) -> Result<()> {
2169        let payload = envelope.payload.clone();
2170        let buffer_id = payload.buffer_id as usize;
2171        let ops = payload
2172            .operations
2173            .into_iter()
2174            .map(|op| language::proto::deserialize_operation(op))
2175            .collect::<Result<Vec<_>, _>>()?;
2176        if let Some(buffer) = self.open_buffers.get_mut(&buffer_id) {
2177            if let Some(buffer) = buffer.upgrade(cx) {
2178                buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
2179            }
2180        }
2181        Ok(())
2182    }
2183
2184    pub fn handle_update_buffer_file(
2185        &mut self,
2186        envelope: TypedEnvelope<proto::UpdateBufferFile>,
2187        _: Arc<Client>,
2188        cx: &mut ModelContext<Self>,
2189    ) -> Result<()> {
2190        let payload = envelope.payload.clone();
2191        let buffer_id = payload.buffer_id as usize;
2192        let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
2193        let worktree = self
2194            .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
2195            .ok_or_else(|| anyhow!("no such worktree"))?;
2196        let file = File::from_proto(file, worktree.clone(), cx)?;
2197        let buffer = self
2198            .open_buffers
2199            .get_mut(&buffer_id)
2200            .and_then(|b| b.upgrade(cx))
2201            .ok_or_else(|| anyhow!("no such buffer"))?;
2202        buffer.update(cx, |buffer, cx| {
2203            buffer.file_updated(Box::new(file), cx).detach();
2204        });
2205
2206        Ok(())
2207    }
2208
2209    pub fn handle_save_buffer(
2210        &mut self,
2211        envelope: TypedEnvelope<proto::SaveBuffer>,
2212        rpc: Arc<Client>,
2213        cx: &mut ModelContext<Self>,
2214    ) -> Result<()> {
2215        let sender_id = envelope.original_sender_id()?;
2216        let project_id = self.remote_id().ok_or_else(|| anyhow!("not connected"))?;
2217        let buffer = self
2218            .shared_buffers
2219            .get(&sender_id)
2220            .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2221            .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2222        let receipt = envelope.receipt();
2223        let buffer_id = envelope.payload.buffer_id;
2224        let save = cx.spawn(|_, mut cx| async move {
2225            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await
2226        });
2227
2228        cx.background()
2229            .spawn(
2230                async move {
2231                    let (version, mtime) = save.await?;
2232
2233                    rpc.respond(
2234                        receipt,
2235                        proto::BufferSaved {
2236                            project_id,
2237                            buffer_id,
2238                            version: (&version).into(),
2239                            mtime: Some(mtime.into()),
2240                        },
2241                    )?;
2242
2243                    Ok(())
2244                }
2245                .log_err(),
2246            )
2247            .detach();
2248        Ok(())
2249    }
2250
2251    pub fn handle_format_buffers(
2252        &mut self,
2253        envelope: TypedEnvelope<proto::FormatBuffers>,
2254        rpc: Arc<Client>,
2255        cx: &mut ModelContext<Self>,
2256    ) -> Result<()> {
2257        let receipt = envelope.receipt();
2258        let sender_id = envelope.original_sender_id()?;
2259        let shared_buffers = self
2260            .shared_buffers
2261            .get(&sender_id)
2262            .ok_or_else(|| anyhow!("peer has no buffers"))?;
2263        let mut buffers = HashSet::default();
2264        for buffer_id in envelope.payload.buffer_ids {
2265            buffers.insert(
2266                shared_buffers
2267                    .get(&buffer_id)
2268                    .cloned()
2269                    .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
2270            );
2271        }
2272        cx.spawn(|this, mut cx| async move {
2273            dbg!("here!");
2274            let project_transaction = this
2275                .update(&mut cx, |this, cx| this.format(buffers, false, cx))
2276                .await
2277                .map(|project_transaction| {
2278                    this.update(&mut cx, |this, cx| {
2279                        this.serialize_project_transaction_for_peer(
2280                            project_transaction,
2281                            sender_id,
2282                            cx,
2283                        )
2284                    })
2285                });
2286            // We spawn here in order to enqueue the sending of the response *after* transmission of
2287            // edits associated with formatting.
2288            cx.spawn(|_| async move {
2289                match project_transaction {
2290                    Ok(transaction) => rpc.respond(
2291                        receipt,
2292                        proto::FormatBuffersResponse {
2293                            transaction: Some(transaction),
2294                        },
2295                    )?,
2296                    Err(error) => rpc.respond_with_error(
2297                        receipt,
2298                        proto::Error {
2299                            message: error.to_string(),
2300                        },
2301                    )?,
2302                }
2303                Ok::<_, anyhow::Error>(())
2304            })
2305            .await
2306            .log_err();
2307        })
2308        .detach();
2309        Ok(())
2310    }
2311
2312    fn handle_get_completions(
2313        &mut self,
2314        envelope: TypedEnvelope<proto::GetCompletions>,
2315        rpc: Arc<Client>,
2316        cx: &mut ModelContext<Self>,
2317    ) -> Result<()> {
2318        let receipt = envelope.receipt();
2319        let sender_id = envelope.original_sender_id()?;
2320        let buffer = self
2321            .shared_buffers
2322            .get(&sender_id)
2323            .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2324            .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2325        let position = envelope
2326            .payload
2327            .position
2328            .and_then(language::proto::deserialize_anchor)
2329            .ok_or_else(|| anyhow!("invalid position"))?;
2330        cx.spawn(|this, mut cx| async move {
2331            match this
2332                .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
2333                .await
2334            {
2335                Ok(completions) => rpc.respond(
2336                    receipt,
2337                    proto::GetCompletionsResponse {
2338                        completions: completions
2339                            .iter()
2340                            .map(language::proto::serialize_completion)
2341                            .collect(),
2342                    },
2343                ),
2344                Err(error) => rpc.respond_with_error(
2345                    receipt,
2346                    proto::Error {
2347                        message: error.to_string(),
2348                    },
2349                ),
2350            }
2351        })
2352        .detach_and_log_err(cx);
2353        Ok(())
2354    }
2355
2356    fn handle_apply_additional_edits_for_completion(
2357        &mut self,
2358        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
2359        rpc: Arc<Client>,
2360        cx: &mut ModelContext<Self>,
2361    ) -> Result<()> {
2362        let receipt = envelope.receipt();
2363        let sender_id = envelope.original_sender_id()?;
2364        let buffer = self
2365            .shared_buffers
2366            .get(&sender_id)
2367            .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2368            .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2369        let language = buffer.read(cx).language();
2370        let completion = language::proto::deserialize_completion(
2371            envelope
2372                .payload
2373                .completion
2374                .ok_or_else(|| anyhow!("invalid completion"))?,
2375            language,
2376        )?;
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            match this
2424                .update(&mut cx, |this, cx| this.code_actions(&buffer, position, cx))
2425                .await
2426            {
2427                Ok(completions) => rpc.respond(
2428                    receipt,
2429                    proto::GetCodeActionsResponse {
2430                        actions: completions
2431                            .iter()
2432                            .map(language::proto::serialize_code_action)
2433                            .collect(),
2434                    },
2435                ),
2436                Err(error) => rpc.respond_with_error(
2437                    receipt,
2438                    proto::Error {
2439                        message: error.to_string(),
2440                    },
2441                ),
2442            }
2443        })
2444        .detach_and_log_err(cx);
2445        Ok(())
2446    }
2447
2448    fn handle_apply_code_action(
2449        &mut self,
2450        envelope: TypedEnvelope<proto::ApplyCodeAction>,
2451        rpc: Arc<Client>,
2452        cx: &mut ModelContext<Self>,
2453    ) -> Result<()> {
2454        let receipt = envelope.receipt();
2455        let sender_id = envelope.original_sender_id()?;
2456        let buffer = self
2457            .shared_buffers
2458            .get(&sender_id)
2459            .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2460            .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2461        let action = language::proto::deserialize_code_action(
2462            envelope
2463                .payload
2464                .action
2465                .ok_or_else(|| anyhow!("invalid action"))?,
2466        )?;
2467        let apply_code_action = self.apply_code_action(buffer, action, false, cx);
2468        cx.spawn(|this, mut cx| async move {
2469            match apply_code_action.await {
2470                Ok(project_transaction) => this.update(&mut cx, |this, cx| {
2471                    let serialized_transaction = this.serialize_project_transaction_for_peer(
2472                        project_transaction,
2473                        sender_id,
2474                        cx,
2475                    );
2476                    rpc.respond(
2477                        receipt,
2478                        proto::ApplyCodeActionResponse {
2479                            transaction: Some(serialized_transaction),
2480                        },
2481                    )
2482                }),
2483                Err(error) => rpc.respond_with_error(
2484                    receipt,
2485                    proto::Error {
2486                        message: error.to_string(),
2487                    },
2488                ),
2489            }
2490        })
2491        .detach_and_log_err(cx);
2492        Ok(())
2493    }
2494
2495    pub fn handle_get_definition(
2496        &mut self,
2497        envelope: TypedEnvelope<proto::GetDefinition>,
2498        rpc: Arc<Client>,
2499        cx: &mut ModelContext<Self>,
2500    ) -> Result<()> {
2501        let receipt = envelope.receipt();
2502        let sender_id = envelope.original_sender_id()?;
2503        let source_buffer = self
2504            .shared_buffers
2505            .get(&sender_id)
2506            .and_then(|shared_buffers| shared_buffers.get(&envelope.payload.buffer_id).cloned())
2507            .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
2508        let position = envelope
2509            .payload
2510            .position
2511            .and_then(deserialize_anchor)
2512            .ok_or_else(|| anyhow!("invalid position"))?;
2513        if !source_buffer.read(cx).can_resolve(&position) {
2514            return Err(anyhow!("cannot resolve position"));
2515        }
2516
2517        let definitions = self.definition(&source_buffer, position, cx);
2518        cx.spawn(|this, mut cx| async move {
2519            let definitions = definitions.await?;
2520            let mut response = proto::GetDefinitionResponse {
2521                definitions: Default::default(),
2522            };
2523            this.update(&mut cx, |this, cx| {
2524                for definition in definitions {
2525                    let buffer =
2526                        this.serialize_buffer_for_peer(&definition.target_buffer, sender_id, cx);
2527                    response.definitions.push(proto::Definition {
2528                        target_start: Some(serialize_anchor(&definition.target_range.start)),
2529                        target_end: Some(serialize_anchor(&definition.target_range.end)),
2530                        buffer: Some(buffer),
2531                    });
2532                }
2533            });
2534            rpc.respond(receipt, response)?;
2535            Ok::<_, anyhow::Error>(())
2536        })
2537        .detach_and_log_err(cx);
2538
2539        Ok(())
2540    }
2541
2542    pub fn handle_open_buffer(
2543        &mut self,
2544        envelope: TypedEnvelope<proto::OpenBuffer>,
2545        rpc: Arc<Client>,
2546        cx: &mut ModelContext<Self>,
2547    ) -> anyhow::Result<()> {
2548        let receipt = envelope.receipt();
2549        let peer_id = envelope.original_sender_id()?;
2550        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
2551        let open_buffer = self.open_buffer(
2552            ProjectPath {
2553                worktree_id,
2554                path: PathBuf::from(envelope.payload.path).into(),
2555            },
2556            cx,
2557        );
2558        cx.spawn(|this, mut cx| {
2559            async move {
2560                let buffer = open_buffer.await?;
2561                let buffer = this.update(&mut cx, |this, cx| {
2562                    this.serialize_buffer_for_peer(&buffer, peer_id, cx)
2563                });
2564                rpc.respond(
2565                    receipt,
2566                    proto::OpenBufferResponse {
2567                        buffer: Some(buffer),
2568                    },
2569                )
2570            }
2571            .log_err()
2572        })
2573        .detach();
2574        Ok(())
2575    }
2576
2577    fn serialize_project_transaction_for_peer(
2578        &mut self,
2579        project_transaction: ProjectTransaction,
2580        peer_id: PeerId,
2581        cx: &AppContext,
2582    ) -> proto::ProjectTransaction {
2583        let mut serialized_transaction = proto::ProjectTransaction {
2584            buffers: Default::default(),
2585            transactions: Default::default(),
2586        };
2587        for (buffer, transaction) in project_transaction.0 {
2588            serialized_transaction
2589                .buffers
2590                .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
2591            serialized_transaction
2592                .transactions
2593                .push(language::proto::serialize_transaction(&transaction));
2594        }
2595        serialized_transaction
2596    }
2597
2598    fn deserialize_project_transaction(
2599        &self,
2600        message: proto::ProjectTransaction,
2601        push_to_history: bool,
2602        cx: &mut ModelContext<Self>,
2603    ) -> Task<Result<ProjectTransaction>> {
2604        cx.spawn(|this, mut cx| async move {
2605            let mut project_transaction = ProjectTransaction::default();
2606            for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
2607                let buffer =
2608                    this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))?;
2609                let transaction = language::proto::deserialize_transaction(transaction)?;
2610
2611                buffer
2612                    .update(&mut cx, |buffer, _| {
2613                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
2614                    })
2615                    .await;
2616
2617                if push_to_history {
2618                    buffer.update(&mut cx, |buffer, _| {
2619                        buffer.push_transaction(transaction.clone(), Instant::now());
2620                    });
2621                }
2622
2623                project_transaction.0.insert(buffer, transaction);
2624            }
2625            Ok(project_transaction)
2626        })
2627    }
2628
2629    fn serialize_buffer_for_peer(
2630        &mut self,
2631        buffer: &ModelHandle<Buffer>,
2632        peer_id: PeerId,
2633        cx: &AppContext,
2634    ) -> proto::Buffer {
2635        let buffer_id = buffer.read(cx).remote_id();
2636        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
2637        match shared_buffers.entry(buffer_id) {
2638            hash_map::Entry::Occupied(_) => proto::Buffer {
2639                variant: Some(proto::buffer::Variant::Id(buffer_id)),
2640            },
2641            hash_map::Entry::Vacant(entry) => {
2642                entry.insert(buffer.clone());
2643                proto::Buffer {
2644                    variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
2645                }
2646            }
2647        }
2648    }
2649
2650    fn deserialize_buffer(
2651        &mut self,
2652        buffer: proto::Buffer,
2653        cx: &mut ModelContext<Self>,
2654    ) -> Result<ModelHandle<Buffer>> {
2655        match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
2656            proto::buffer::Variant::Id(id) => self
2657                .open_buffers
2658                .get(&(id as usize))
2659                .and_then(|buffer| buffer.upgrade(cx))
2660                .ok_or_else(|| anyhow!("no buffer exists for id {}", id)),
2661            proto::buffer::Variant::State(mut buffer) => {
2662                let mut buffer_worktree = None;
2663                let mut buffer_file = None;
2664                if let Some(file) = buffer.file.take() {
2665                    let worktree_id = WorktreeId::from_proto(file.worktree_id);
2666                    let worktree = self
2667                        .worktree_for_id(worktree_id, cx)
2668                        .ok_or_else(|| anyhow!("no worktree found for id {}", file.worktree_id))?;
2669                    buffer_file = Some(Box::new(File::from_proto(file, worktree.clone(), cx)?)
2670                        as Box<dyn language::File>);
2671                    buffer_worktree = Some(worktree);
2672                }
2673
2674                let buffer = cx.add_model(|cx| {
2675                    Buffer::from_proto(self.replica_id(), buffer, buffer_file, cx).unwrap()
2676                });
2677                self.register_buffer(&buffer, buffer_worktree.as_ref(), cx)?;
2678                Ok(buffer)
2679            }
2680        }
2681    }
2682
2683    pub fn handle_close_buffer(
2684        &mut self,
2685        envelope: TypedEnvelope<proto::CloseBuffer>,
2686        _: Arc<Client>,
2687        cx: &mut ModelContext<Self>,
2688    ) -> anyhow::Result<()> {
2689        if let Some(shared_buffers) = self.shared_buffers.get_mut(&envelope.original_sender_id()?) {
2690            shared_buffers.remove(&envelope.payload.buffer_id);
2691            cx.notify();
2692        }
2693        Ok(())
2694    }
2695
2696    pub fn handle_buffer_saved(
2697        &mut self,
2698        envelope: TypedEnvelope<proto::BufferSaved>,
2699        _: Arc<Client>,
2700        cx: &mut ModelContext<Self>,
2701    ) -> Result<()> {
2702        let payload = envelope.payload.clone();
2703        let buffer = self
2704            .open_buffers
2705            .get(&(payload.buffer_id as usize))
2706            .and_then(|buffer| buffer.upgrade(cx));
2707        if let Some(buffer) = buffer {
2708            buffer.update(cx, |buffer, cx| {
2709                let version = payload.version.try_into()?;
2710                let mtime = payload
2711                    .mtime
2712                    .ok_or_else(|| anyhow!("missing mtime"))?
2713                    .into();
2714                buffer.did_save(version, mtime, None, cx);
2715                Result::<_, anyhow::Error>::Ok(())
2716            })?;
2717        }
2718        Ok(())
2719    }
2720
2721    pub fn handle_buffer_reloaded(
2722        &mut self,
2723        envelope: TypedEnvelope<proto::BufferReloaded>,
2724        _: Arc<Client>,
2725        cx: &mut ModelContext<Self>,
2726    ) -> Result<()> {
2727        let payload = envelope.payload.clone();
2728        let buffer = self
2729            .open_buffers
2730            .get(&(payload.buffer_id as usize))
2731            .and_then(|buffer| buffer.upgrade(cx));
2732        if let Some(buffer) = buffer {
2733            buffer.update(cx, |buffer, cx| {
2734                let version = payload.version.try_into()?;
2735                let mtime = payload
2736                    .mtime
2737                    .ok_or_else(|| anyhow!("missing mtime"))?
2738                    .into();
2739                buffer.did_reload(version, mtime, cx);
2740                Result::<_, anyhow::Error>::Ok(())
2741            })?;
2742        }
2743        Ok(())
2744    }
2745
2746    pub fn match_paths<'a>(
2747        &self,
2748        query: &'a str,
2749        include_ignored: bool,
2750        smart_case: bool,
2751        max_results: usize,
2752        cancel_flag: &'a AtomicBool,
2753        cx: &AppContext,
2754    ) -> impl 'a + Future<Output = Vec<PathMatch>> {
2755        let worktrees = self
2756            .worktrees(cx)
2757            .filter(|worktree| !worktree.read(cx).is_weak())
2758            .collect::<Vec<_>>();
2759        let include_root_name = worktrees.len() > 1;
2760        let candidate_sets = worktrees
2761            .into_iter()
2762            .map(|worktree| CandidateSet {
2763                snapshot: worktree.read(cx).snapshot(),
2764                include_ignored,
2765                include_root_name,
2766            })
2767            .collect::<Vec<_>>();
2768
2769        let background = cx.background().clone();
2770        async move {
2771            fuzzy::match_paths(
2772                candidate_sets.as_slice(),
2773                query,
2774                smart_case,
2775                max_results,
2776                cancel_flag,
2777                background,
2778            )
2779            .await
2780        }
2781    }
2782}
2783
2784impl WorktreeHandle {
2785    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
2786        match self {
2787            WorktreeHandle::Strong(handle) => Some(handle.clone()),
2788            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
2789        }
2790    }
2791}
2792
2793struct CandidateSet {
2794    snapshot: Snapshot,
2795    include_ignored: bool,
2796    include_root_name: bool,
2797}
2798
2799impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
2800    type Candidates = CandidateSetIter<'a>;
2801
2802    fn id(&self) -> usize {
2803        self.snapshot.id().to_usize()
2804    }
2805
2806    fn len(&self) -> usize {
2807        if self.include_ignored {
2808            self.snapshot.file_count()
2809        } else {
2810            self.snapshot.visible_file_count()
2811        }
2812    }
2813
2814    fn prefix(&self) -> Arc<str> {
2815        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
2816            self.snapshot.root_name().into()
2817        } else if self.include_root_name {
2818            format!("{}/", self.snapshot.root_name()).into()
2819        } else {
2820            "".into()
2821        }
2822    }
2823
2824    fn candidates(&'a self, start: usize) -> Self::Candidates {
2825        CandidateSetIter {
2826            traversal: self.snapshot.files(self.include_ignored, start),
2827        }
2828    }
2829}
2830
2831struct CandidateSetIter<'a> {
2832    traversal: Traversal<'a>,
2833}
2834
2835impl<'a> Iterator for CandidateSetIter<'a> {
2836    type Item = PathMatchCandidate<'a>;
2837
2838    fn next(&mut self) -> Option<Self::Item> {
2839        self.traversal.next().map(|entry| {
2840            if let EntryKind::File(char_bag) = entry.kind {
2841                PathMatchCandidate {
2842                    path: &entry.path,
2843                    char_bag,
2844                }
2845            } else {
2846                unreachable!()
2847            }
2848        })
2849    }
2850}
2851
2852impl Entity for Project {
2853    type Event = Event;
2854
2855    fn release(&mut self, _: &mut gpui::MutableAppContext) {
2856        match &self.client_state {
2857            ProjectClientState::Local { remote_id_rx, .. } => {
2858                if let Some(project_id) = *remote_id_rx.borrow() {
2859                    self.client
2860                        .send(proto::UnregisterProject { project_id })
2861                        .log_err();
2862                }
2863            }
2864            ProjectClientState::Remote { remote_id, .. } => {
2865                self.client
2866                    .send(proto::LeaveProject {
2867                        project_id: *remote_id,
2868                    })
2869                    .log_err();
2870            }
2871        }
2872    }
2873
2874    fn app_will_quit(
2875        &mut self,
2876        _: &mut MutableAppContext,
2877    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
2878        use futures::FutureExt;
2879
2880        let shutdown_futures = self
2881            .language_servers
2882            .drain()
2883            .filter_map(|(_, server)| server.shutdown())
2884            .collect::<Vec<_>>();
2885        Some(
2886            async move {
2887                futures::future::join_all(shutdown_futures).await;
2888            }
2889            .boxed(),
2890        )
2891    }
2892}
2893
2894impl Collaborator {
2895    fn from_proto(
2896        message: proto::Collaborator,
2897        user_store: &ModelHandle<UserStore>,
2898        cx: &mut AsyncAppContext,
2899    ) -> impl Future<Output = Result<Self>> {
2900        let user = user_store.update(cx, |user_store, cx| {
2901            user_store.fetch_user(message.user_id, cx)
2902        });
2903
2904        async move {
2905            Ok(Self {
2906                peer_id: PeerId(message.peer_id),
2907                user: user.await?,
2908                replica_id: message.replica_id as ReplicaId,
2909            })
2910        }
2911    }
2912}
2913
2914impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
2915    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
2916        Self {
2917            worktree_id,
2918            path: path.as_ref().into(),
2919        }
2920    }
2921}
2922
2923impl From<lsp::CreateFileOptions> for fs::CreateOptions {
2924    fn from(options: lsp::CreateFileOptions) -> Self {
2925        Self {
2926            overwrite: options.overwrite.unwrap_or(false),
2927            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2928        }
2929    }
2930}
2931
2932impl From<lsp::RenameFileOptions> for fs::RenameOptions {
2933    fn from(options: lsp::RenameFileOptions) -> Self {
2934        Self {
2935            overwrite: options.overwrite.unwrap_or(false),
2936            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
2937        }
2938    }
2939}
2940
2941impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
2942    fn from(options: lsp::DeleteFileOptions) -> Self {
2943        Self {
2944            recursive: options.recursive.unwrap_or(false),
2945            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
2946        }
2947    }
2948}
2949
2950#[cfg(test)]
2951mod tests {
2952    use super::{Event, *};
2953    use client::test::FakeHttpClient;
2954    use fs::RealFs;
2955    use futures::StreamExt;
2956    use gpui::test::subscribe;
2957    use language::{
2958        tree_sitter_rust, AnchorRangeExt, Diagnostic, LanguageConfig, LanguageRegistry,
2959        LanguageServerConfig, Point,
2960    };
2961    use lsp::Url;
2962    use serde_json::json;
2963    use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc};
2964    use unindent::Unindent as _;
2965    use util::test::temp_tree;
2966    use worktree::WorktreeHandle as _;
2967
2968    #[gpui::test]
2969    async fn test_populate_and_search(mut cx: gpui::TestAppContext) {
2970        let dir = temp_tree(json!({
2971            "root": {
2972                "apple": "",
2973                "banana": {
2974                    "carrot": {
2975                        "date": "",
2976                        "endive": "",
2977                    }
2978                },
2979                "fennel": {
2980                    "grape": "",
2981                }
2982            }
2983        }));
2984
2985        let root_link_path = dir.path().join("root_link");
2986        unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
2987        unix::fs::symlink(
2988            &dir.path().join("root/fennel"),
2989            &dir.path().join("root/finnochio"),
2990        )
2991        .unwrap();
2992
2993        let project = Project::test(Arc::new(RealFs), &mut cx);
2994
2995        let (tree, _) = project
2996            .update(&mut cx, |project, cx| {
2997                project.find_or_create_local_worktree(&root_link_path, false, cx)
2998            })
2999            .await
3000            .unwrap();
3001
3002        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3003            .await;
3004        cx.read(|cx| {
3005            let tree = tree.read(cx);
3006            assert_eq!(tree.file_count(), 5);
3007            assert_eq!(
3008                tree.inode_for_path("fennel/grape"),
3009                tree.inode_for_path("finnochio/grape")
3010            );
3011        });
3012
3013        let cancel_flag = Default::default();
3014        let results = project
3015            .read_with(&cx, |project, cx| {
3016                project.match_paths("bna", false, false, 10, &cancel_flag, cx)
3017            })
3018            .await;
3019        assert_eq!(
3020            results
3021                .into_iter()
3022                .map(|result| result.path)
3023                .collect::<Vec<Arc<Path>>>(),
3024            vec![
3025                PathBuf::from("banana/carrot/date").into(),
3026                PathBuf::from("banana/carrot/endive").into(),
3027            ]
3028        );
3029    }
3030
3031    #[gpui::test]
3032    async fn test_language_server_diagnostics(mut cx: gpui::TestAppContext) {
3033        let (language_server_config, mut fake_server) = LanguageServerConfig::fake(&cx).await;
3034        let progress_token = language_server_config
3035            .disk_based_diagnostics_progress_token
3036            .clone()
3037            .unwrap();
3038
3039        let mut languages = LanguageRegistry::new();
3040        languages.add(Arc::new(Language::new(
3041            LanguageConfig {
3042                name: "Rust".to_string(),
3043                path_suffixes: vec!["rs".to_string()],
3044                language_server: Some(language_server_config),
3045                ..Default::default()
3046            },
3047            Some(tree_sitter_rust::language()),
3048        )));
3049
3050        let dir = temp_tree(json!({
3051            "a.rs": "fn a() { A }",
3052            "b.rs": "const y: i32 = 1",
3053        }));
3054
3055        let http_client = FakeHttpClient::with_404_response();
3056        let client = Client::new(http_client.clone());
3057        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3058
3059        let project = cx.update(|cx| {
3060            Project::local(
3061                client,
3062                user_store,
3063                Arc::new(languages),
3064                Arc::new(RealFs),
3065                cx,
3066            )
3067        });
3068
3069        let (tree, _) = project
3070            .update(&mut cx, |project, cx| {
3071                project.find_or_create_local_worktree(dir.path(), false, cx)
3072            })
3073            .await
3074            .unwrap();
3075        let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3076
3077        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3078            .await;
3079
3080        // Cause worktree to start the fake language server
3081        let _buffer = project
3082            .update(&mut cx, |project, cx| {
3083                project.open_buffer(
3084                    ProjectPath {
3085                        worktree_id,
3086                        path: Path::new("b.rs").into(),
3087                    },
3088                    cx,
3089                )
3090            })
3091            .await
3092            .unwrap();
3093
3094        let mut events = subscribe(&project, &mut cx);
3095
3096        fake_server.start_progress(&progress_token).await;
3097        assert_eq!(
3098            events.next().await.unwrap(),
3099            Event::DiskBasedDiagnosticsStarted
3100        );
3101
3102        fake_server.start_progress(&progress_token).await;
3103        fake_server.end_progress(&progress_token).await;
3104        fake_server.start_progress(&progress_token).await;
3105
3106        fake_server
3107            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
3108                uri: Url::from_file_path(dir.path().join("a.rs")).unwrap(),
3109                version: None,
3110                diagnostics: vec![lsp::Diagnostic {
3111                    range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3112                    severity: Some(lsp::DiagnosticSeverity::ERROR),
3113                    message: "undefined variable 'A'".to_string(),
3114                    ..Default::default()
3115                }],
3116            })
3117            .await;
3118        assert_eq!(
3119            events.next().await.unwrap(),
3120            Event::DiagnosticsUpdated(ProjectPath {
3121                worktree_id,
3122                path: Arc::from(Path::new("a.rs"))
3123            })
3124        );
3125
3126        fake_server.end_progress(&progress_token).await;
3127        fake_server.end_progress(&progress_token).await;
3128        assert_eq!(
3129            events.next().await.unwrap(),
3130            Event::DiskBasedDiagnosticsUpdated
3131        );
3132        assert_eq!(
3133            events.next().await.unwrap(),
3134            Event::DiskBasedDiagnosticsFinished
3135        );
3136
3137        let buffer = project
3138            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3139            .await
3140            .unwrap();
3141
3142        buffer.read_with(&cx, |buffer, _| {
3143            let snapshot = buffer.snapshot();
3144            let diagnostics = snapshot
3145                .diagnostics_in_range::<_, Point>(0..buffer.len())
3146                .collect::<Vec<_>>();
3147            assert_eq!(
3148                diagnostics,
3149                &[DiagnosticEntry {
3150                    range: Point::new(0, 9)..Point::new(0, 10),
3151                    diagnostic: Diagnostic {
3152                        severity: lsp::DiagnosticSeverity::ERROR,
3153                        message: "undefined variable 'A'".to_string(),
3154                        group_id: 0,
3155                        is_primary: true,
3156                        ..Default::default()
3157                    }
3158                }]
3159            )
3160        });
3161    }
3162
3163    #[gpui::test]
3164    async fn test_search_worktree_without_files(mut cx: gpui::TestAppContext) {
3165        let dir = temp_tree(json!({
3166            "root": {
3167                "dir1": {},
3168                "dir2": {
3169                    "dir3": {}
3170                }
3171            }
3172        }));
3173
3174        let project = Project::test(Arc::new(RealFs), &mut cx);
3175        let (tree, _) = project
3176            .update(&mut cx, |project, cx| {
3177                project.find_or_create_local_worktree(&dir.path(), false, cx)
3178            })
3179            .await
3180            .unwrap();
3181
3182        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3183            .await;
3184
3185        let cancel_flag = Default::default();
3186        let results = project
3187            .read_with(&cx, |project, cx| {
3188                project.match_paths("dir", false, false, 10, &cancel_flag, cx)
3189            })
3190            .await;
3191
3192        assert!(results.is_empty());
3193    }
3194
3195    #[gpui::test]
3196    async fn test_definition(mut cx: gpui::TestAppContext) {
3197        let (language_server_config, mut fake_server) = LanguageServerConfig::fake(&cx).await;
3198
3199        let mut languages = LanguageRegistry::new();
3200        languages.add(Arc::new(Language::new(
3201            LanguageConfig {
3202                name: "Rust".to_string(),
3203                path_suffixes: vec!["rs".to_string()],
3204                language_server: Some(language_server_config),
3205                ..Default::default()
3206            },
3207            Some(tree_sitter_rust::language()),
3208        )));
3209
3210        let dir = temp_tree(json!({
3211            "a.rs": "const fn a() { A }",
3212            "b.rs": "const y: i32 = crate::a()",
3213        }));
3214
3215        let http_client = FakeHttpClient::with_404_response();
3216        let client = Client::new(http_client.clone());
3217        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
3218        let project = cx.update(|cx| {
3219            Project::local(
3220                client,
3221                user_store,
3222                Arc::new(languages),
3223                Arc::new(RealFs),
3224                cx,
3225            )
3226        });
3227
3228        let (tree, _) = project
3229            .update(&mut cx, |project, cx| {
3230                project.find_or_create_local_worktree(dir.path().join("b.rs"), false, cx)
3231            })
3232            .await
3233            .unwrap();
3234        let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3235        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3236            .await;
3237
3238        // Cause worktree to start the fake language server
3239        let buffer = project
3240            .update(&mut cx, |project, cx| {
3241                project.open_buffer(
3242                    ProjectPath {
3243                        worktree_id,
3244                        path: Path::new("").into(),
3245                    },
3246                    cx,
3247                )
3248            })
3249            .await
3250            .unwrap();
3251        let definitions =
3252            project.update(&mut cx, |project, cx| project.definition(&buffer, 22, cx));
3253        let (request_id, request) = fake_server
3254            .receive_request::<lsp::request::GotoDefinition>()
3255            .await;
3256        let request_params = request.text_document_position_params;
3257        assert_eq!(
3258            request_params.text_document.uri.to_file_path().unwrap(),
3259            dir.path().join("b.rs")
3260        );
3261        assert_eq!(request_params.position, lsp::Position::new(0, 22));
3262
3263        fake_server
3264            .respond(
3265                request_id,
3266                Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
3267                    lsp::Url::from_file_path(dir.path().join("a.rs")).unwrap(),
3268                    lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
3269                ))),
3270            )
3271            .await;
3272        let mut definitions = definitions.await.unwrap();
3273        assert_eq!(definitions.len(), 1);
3274        let definition = definitions.pop().unwrap();
3275        cx.update(|cx| {
3276            let target_buffer = definition.target_buffer.read(cx);
3277            assert_eq!(
3278                target_buffer
3279                    .file()
3280                    .unwrap()
3281                    .as_local()
3282                    .unwrap()
3283                    .abs_path(cx),
3284                dir.path().join("a.rs")
3285            );
3286            assert_eq!(definition.target_range.to_offset(target_buffer), 9..10);
3287            assert_eq!(
3288                list_worktrees(&project, cx),
3289                [
3290                    (dir.path().join("b.rs"), false),
3291                    (dir.path().join("a.rs"), true)
3292                ]
3293            );
3294
3295            drop(definition);
3296        });
3297        cx.read(|cx| {
3298            assert_eq!(
3299                list_worktrees(&project, cx),
3300                [(dir.path().join("b.rs"), false)]
3301            );
3302        });
3303
3304        fn list_worktrees(project: &ModelHandle<Project>, cx: &AppContext) -> Vec<(PathBuf, bool)> {
3305            project
3306                .read(cx)
3307                .worktrees(cx)
3308                .map(|worktree| {
3309                    let worktree = worktree.read(cx);
3310                    (
3311                        worktree.as_local().unwrap().abs_path().to_path_buf(),
3312                        worktree.is_weak(),
3313                    )
3314                })
3315                .collect::<Vec<_>>()
3316        }
3317    }
3318
3319    #[gpui::test]
3320    async fn test_save_file(mut cx: gpui::TestAppContext) {
3321        let fs = Arc::new(FakeFs::new(cx.background()));
3322        fs.insert_tree(
3323            "/dir",
3324            json!({
3325                "file1": "the old contents",
3326            }),
3327        )
3328        .await;
3329
3330        let project = Project::test(fs.clone(), &mut cx);
3331        let worktree_id = project
3332            .update(&mut cx, |p, cx| {
3333                p.find_or_create_local_worktree("/dir", false, cx)
3334            })
3335            .await
3336            .unwrap()
3337            .0
3338            .read_with(&cx, |tree, _| tree.id());
3339
3340        let buffer = project
3341            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
3342            .await
3343            .unwrap();
3344        buffer
3345            .update(&mut cx, |buffer, cx| {
3346                assert_eq!(buffer.text(), "the old contents");
3347                buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3348                buffer.save(cx)
3349            })
3350            .await
3351            .unwrap();
3352
3353        let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
3354        assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3355    }
3356
3357    #[gpui::test]
3358    async fn test_save_in_single_file_worktree(mut cx: gpui::TestAppContext) {
3359        let fs = Arc::new(FakeFs::new(cx.background()));
3360        fs.insert_tree(
3361            "/dir",
3362            json!({
3363                "file1": "the old contents",
3364            }),
3365        )
3366        .await;
3367
3368        let project = Project::test(fs.clone(), &mut cx);
3369        let worktree_id = project
3370            .update(&mut cx, |p, cx| {
3371                p.find_or_create_local_worktree("/dir/file1", false, cx)
3372            })
3373            .await
3374            .unwrap()
3375            .0
3376            .read_with(&cx, |tree, _| tree.id());
3377
3378        let buffer = project
3379            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, ""), cx))
3380            .await
3381            .unwrap();
3382        buffer
3383            .update(&mut cx, |buffer, cx| {
3384                buffer.edit(Some(0..0), "a line of text.\n".repeat(10 * 1024), cx);
3385                buffer.save(cx)
3386            })
3387            .await
3388            .unwrap();
3389
3390        let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
3391        assert_eq!(new_text, buffer.read_with(&cx, |buffer, _| buffer.text()));
3392    }
3393
3394    #[gpui::test(retries = 5)]
3395    async fn test_rescan_and_remote_updates(mut cx: gpui::TestAppContext) {
3396        let dir = temp_tree(json!({
3397            "a": {
3398                "file1": "",
3399                "file2": "",
3400                "file3": "",
3401            },
3402            "b": {
3403                "c": {
3404                    "file4": "",
3405                    "file5": "",
3406                }
3407            }
3408        }));
3409
3410        let project = Project::test(Arc::new(RealFs), &mut cx);
3411        let rpc = project.read_with(&cx, |p, _| p.client.clone());
3412
3413        let (tree, _) = project
3414            .update(&mut cx, |p, cx| {
3415                p.find_or_create_local_worktree(dir.path(), false, cx)
3416            })
3417            .await
3418            .unwrap();
3419        let worktree_id = tree.read_with(&cx, |tree, _| tree.id());
3420
3421        let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
3422            let buffer = project.update(cx, |p, cx| p.open_buffer((worktree_id, path), cx));
3423            async move { buffer.await.unwrap() }
3424        };
3425        let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
3426            tree.read_with(cx, |tree, _| {
3427                tree.entry_for_path(path)
3428                    .expect(&format!("no entry for path {}", path))
3429                    .id
3430            })
3431        };
3432
3433        let buffer2 = buffer_for_path("a/file2", &mut cx).await;
3434        let buffer3 = buffer_for_path("a/file3", &mut cx).await;
3435        let buffer4 = buffer_for_path("b/c/file4", &mut cx).await;
3436        let buffer5 = buffer_for_path("b/c/file5", &mut cx).await;
3437
3438        let file2_id = id_for_path("a/file2", &cx);
3439        let file3_id = id_for_path("a/file3", &cx);
3440        let file4_id = id_for_path("b/c/file4", &cx);
3441
3442        // Wait for the initial scan.
3443        cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
3444            .await;
3445
3446        // Create a remote copy of this worktree.
3447        let initial_snapshot = tree.read_with(&cx, |tree, _| tree.snapshot());
3448        let (remote, load_task) = cx.update(|cx| {
3449            Worktree::remote(
3450                1,
3451                1,
3452                initial_snapshot.to_proto(&Default::default(), Default::default()),
3453                rpc.clone(),
3454                cx,
3455            )
3456        });
3457        load_task.await;
3458
3459        cx.read(|cx| {
3460            assert!(!buffer2.read(cx).is_dirty());
3461            assert!(!buffer3.read(cx).is_dirty());
3462            assert!(!buffer4.read(cx).is_dirty());
3463            assert!(!buffer5.read(cx).is_dirty());
3464        });
3465
3466        // Rename and delete files and directories.
3467        tree.flush_fs_events(&cx).await;
3468        std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
3469        std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
3470        std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
3471        std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
3472        tree.flush_fs_events(&cx).await;
3473
3474        let expected_paths = vec![
3475            "a",
3476            "a/file1",
3477            "a/file2.new",
3478            "b",
3479            "d",
3480            "d/file3",
3481            "d/file4",
3482        ];
3483
3484        cx.read(|app| {
3485            assert_eq!(
3486                tree.read(app)
3487                    .paths()
3488                    .map(|p| p.to_str().unwrap())
3489                    .collect::<Vec<_>>(),
3490                expected_paths
3491            );
3492
3493            assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
3494            assert_eq!(id_for_path("d/file3", &cx), file3_id);
3495            assert_eq!(id_for_path("d/file4", &cx), file4_id);
3496
3497            assert_eq!(
3498                buffer2.read(app).file().unwrap().path().as_ref(),
3499                Path::new("a/file2.new")
3500            );
3501            assert_eq!(
3502                buffer3.read(app).file().unwrap().path().as_ref(),
3503                Path::new("d/file3")
3504            );
3505            assert_eq!(
3506                buffer4.read(app).file().unwrap().path().as_ref(),
3507                Path::new("d/file4")
3508            );
3509            assert_eq!(
3510                buffer5.read(app).file().unwrap().path().as_ref(),
3511                Path::new("b/c/file5")
3512            );
3513
3514            assert!(!buffer2.read(app).file().unwrap().is_deleted());
3515            assert!(!buffer3.read(app).file().unwrap().is_deleted());
3516            assert!(!buffer4.read(app).file().unwrap().is_deleted());
3517            assert!(buffer5.read(app).file().unwrap().is_deleted());
3518        });
3519
3520        // Update the remote worktree. Check that it becomes consistent with the
3521        // local worktree.
3522        remote.update(&mut cx, |remote, cx| {
3523            let update_message =
3524                tree.read(cx)
3525                    .snapshot()
3526                    .build_update(&initial_snapshot, 1, 1, true);
3527            remote
3528                .as_remote_mut()
3529                .unwrap()
3530                .snapshot
3531                .apply_remote_update(update_message)
3532                .unwrap();
3533
3534            assert_eq!(
3535                remote
3536                    .paths()
3537                    .map(|p| p.to_str().unwrap())
3538                    .collect::<Vec<_>>(),
3539                expected_paths
3540            );
3541        });
3542    }
3543
3544    #[gpui::test]
3545    async fn test_buffer_deduping(mut cx: gpui::TestAppContext) {
3546        let fs = Arc::new(FakeFs::new(cx.background()));
3547        fs.insert_tree(
3548            "/the-dir",
3549            json!({
3550                "a.txt": "a-contents",
3551                "b.txt": "b-contents",
3552            }),
3553        )
3554        .await;
3555
3556        let project = Project::test(fs.clone(), &mut cx);
3557        let worktree_id = project
3558            .update(&mut cx, |p, cx| {
3559                p.find_or_create_local_worktree("/the-dir", false, cx)
3560            })
3561            .await
3562            .unwrap()
3563            .0
3564            .read_with(&cx, |tree, _| tree.id());
3565
3566        // Spawn multiple tasks to open paths, repeating some paths.
3567        let (buffer_a_1, buffer_b, buffer_a_2) = project.update(&mut cx, |p, cx| {
3568            (
3569                p.open_buffer((worktree_id, "a.txt"), cx),
3570                p.open_buffer((worktree_id, "b.txt"), cx),
3571                p.open_buffer((worktree_id, "a.txt"), cx),
3572            )
3573        });
3574
3575        let buffer_a_1 = buffer_a_1.await.unwrap();
3576        let buffer_a_2 = buffer_a_2.await.unwrap();
3577        let buffer_b = buffer_b.await.unwrap();
3578        assert_eq!(buffer_a_1.read_with(&cx, |b, _| b.text()), "a-contents");
3579        assert_eq!(buffer_b.read_with(&cx, |b, _| b.text()), "b-contents");
3580
3581        // There is only one buffer per path.
3582        let buffer_a_id = buffer_a_1.id();
3583        assert_eq!(buffer_a_2.id(), buffer_a_id);
3584
3585        // Open the same path again while it is still open.
3586        drop(buffer_a_1);
3587        let buffer_a_3 = project
3588            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3589            .await
3590            .unwrap();
3591
3592        // There's still only one buffer per path.
3593        assert_eq!(buffer_a_3.id(), buffer_a_id);
3594    }
3595
3596    #[gpui::test]
3597    async fn test_buffer_is_dirty(mut cx: gpui::TestAppContext) {
3598        use std::fs;
3599
3600        let dir = temp_tree(json!({
3601            "file1": "abc",
3602            "file2": "def",
3603            "file3": "ghi",
3604        }));
3605
3606        let project = Project::test(Arc::new(RealFs), &mut cx);
3607        let (worktree, _) = project
3608            .update(&mut cx, |p, cx| {
3609                p.find_or_create_local_worktree(dir.path(), false, cx)
3610            })
3611            .await
3612            .unwrap();
3613        let worktree_id = worktree.read_with(&cx, |worktree, _| worktree.id());
3614
3615        worktree.flush_fs_events(&cx).await;
3616        worktree
3617            .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
3618            .await;
3619
3620        let buffer1 = project
3621            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
3622            .await
3623            .unwrap();
3624        let events = Rc::new(RefCell::new(Vec::new()));
3625
3626        // initially, the buffer isn't dirty.
3627        buffer1.update(&mut cx, |buffer, cx| {
3628            cx.subscribe(&buffer1, {
3629                let events = events.clone();
3630                move |_, _, event, _| events.borrow_mut().push(event.clone())
3631            })
3632            .detach();
3633
3634            assert!(!buffer.is_dirty());
3635            assert!(events.borrow().is_empty());
3636
3637            buffer.edit(vec![1..2], "", cx);
3638        });
3639
3640        // after the first edit, the buffer is dirty, and emits a dirtied event.
3641        buffer1.update(&mut cx, |buffer, cx| {
3642            assert!(buffer.text() == "ac");
3643            assert!(buffer.is_dirty());
3644            assert_eq!(
3645                *events.borrow(),
3646                &[language::Event::Edited, language::Event::Dirtied]
3647            );
3648            events.borrow_mut().clear();
3649            buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
3650        });
3651
3652        // after saving, the buffer is not dirty, and emits a saved event.
3653        buffer1.update(&mut cx, |buffer, cx| {
3654            assert!(!buffer.is_dirty());
3655            assert_eq!(*events.borrow(), &[language::Event::Saved]);
3656            events.borrow_mut().clear();
3657
3658            buffer.edit(vec![1..1], "B", cx);
3659            buffer.edit(vec![2..2], "D", cx);
3660        });
3661
3662        // after editing again, the buffer is dirty, and emits another dirty event.
3663        buffer1.update(&mut cx, |buffer, cx| {
3664            assert!(buffer.text() == "aBDc");
3665            assert!(buffer.is_dirty());
3666            assert_eq!(
3667                *events.borrow(),
3668                &[
3669                    language::Event::Edited,
3670                    language::Event::Dirtied,
3671                    language::Event::Edited,
3672                ],
3673            );
3674            events.borrow_mut().clear();
3675
3676            // TODO - currently, after restoring the buffer to its
3677            // previously-saved state, the is still considered dirty.
3678            buffer.edit([1..3], "", cx);
3679            assert!(buffer.text() == "ac");
3680            assert!(buffer.is_dirty());
3681        });
3682
3683        assert_eq!(*events.borrow(), &[language::Event::Edited]);
3684
3685        // When a file is deleted, the buffer is considered dirty.
3686        let events = Rc::new(RefCell::new(Vec::new()));
3687        let buffer2 = project
3688            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file2"), cx))
3689            .await
3690            .unwrap();
3691        buffer2.update(&mut cx, |_, cx| {
3692            cx.subscribe(&buffer2, {
3693                let events = events.clone();
3694                move |_, _, event, _| events.borrow_mut().push(event.clone())
3695            })
3696            .detach();
3697        });
3698
3699        fs::remove_file(dir.path().join("file2")).unwrap();
3700        buffer2.condition(&cx, |b, _| b.is_dirty()).await;
3701        assert_eq!(
3702            *events.borrow(),
3703            &[language::Event::Dirtied, language::Event::FileHandleChanged]
3704        );
3705
3706        // When a file is already dirty when deleted, we don't emit a Dirtied event.
3707        let events = Rc::new(RefCell::new(Vec::new()));
3708        let buffer3 = project
3709            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "file3"), cx))
3710            .await
3711            .unwrap();
3712        buffer3.update(&mut cx, |_, cx| {
3713            cx.subscribe(&buffer3, {
3714                let events = events.clone();
3715                move |_, _, event, _| events.borrow_mut().push(event.clone())
3716            })
3717            .detach();
3718        });
3719
3720        worktree.flush_fs_events(&cx).await;
3721        buffer3.update(&mut cx, |buffer, cx| {
3722            buffer.edit(Some(0..0), "x", cx);
3723        });
3724        events.borrow_mut().clear();
3725        fs::remove_file(dir.path().join("file3")).unwrap();
3726        buffer3
3727            .condition(&cx, |_, _| !events.borrow().is_empty())
3728            .await;
3729        assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
3730        cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
3731    }
3732
3733    #[gpui::test]
3734    async fn test_buffer_file_changes_on_disk(mut cx: gpui::TestAppContext) {
3735        use std::fs;
3736
3737        let initial_contents = "aaa\nbbbbb\nc\n";
3738        let dir = temp_tree(json!({ "the-file": initial_contents }));
3739
3740        let project = Project::test(Arc::new(RealFs), &mut cx);
3741        let (worktree, _) = project
3742            .update(&mut cx, |p, cx| {
3743                p.find_or_create_local_worktree(dir.path(), false, cx)
3744            })
3745            .await
3746            .unwrap();
3747        let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
3748
3749        worktree
3750            .read_with(&cx, |t, _| t.as_local().unwrap().scan_complete())
3751            .await;
3752
3753        let abs_path = dir.path().join("the-file");
3754        let buffer = project
3755            .update(&mut cx, |p, cx| {
3756                p.open_buffer((worktree_id, "the-file"), cx)
3757            })
3758            .await
3759            .unwrap();
3760
3761        // TODO
3762        // Add a cursor on each row.
3763        // let selection_set_id = buffer.update(&mut cx, |buffer, cx| {
3764        //     assert!(!buffer.is_dirty());
3765        //     buffer.add_selection_set(
3766        //         &(0..3)
3767        //             .map(|row| Selection {
3768        //                 id: row as usize,
3769        //                 start: Point::new(row, 1),
3770        //                 end: Point::new(row, 1),
3771        //                 reversed: false,
3772        //                 goal: SelectionGoal::None,
3773        //             })
3774        //             .collect::<Vec<_>>(),
3775        //         cx,
3776        //     )
3777        // });
3778
3779        // Change the file on disk, adding two new lines of text, and removing
3780        // one line.
3781        buffer.read_with(&cx, |buffer, _| {
3782            assert!(!buffer.is_dirty());
3783            assert!(!buffer.has_conflict());
3784        });
3785        let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
3786        fs::write(&abs_path, new_contents).unwrap();
3787
3788        // Because the buffer was not modified, it is reloaded from disk. Its
3789        // contents are edited according to the diff between the old and new
3790        // file contents.
3791        buffer
3792            .condition(&cx, |buffer, _| buffer.text() == new_contents)
3793            .await;
3794
3795        buffer.update(&mut cx, |buffer, _| {
3796            assert_eq!(buffer.text(), new_contents);
3797            assert!(!buffer.is_dirty());
3798            assert!(!buffer.has_conflict());
3799
3800            // TODO
3801            // let cursor_positions = buffer
3802            //     .selection_set(selection_set_id)
3803            //     .unwrap()
3804            //     .selections::<Point>(&*buffer)
3805            //     .map(|selection| {
3806            //         assert_eq!(selection.start, selection.end);
3807            //         selection.start
3808            //     })
3809            //     .collect::<Vec<_>>();
3810            // assert_eq!(
3811            //     cursor_positions,
3812            //     [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
3813            // );
3814        });
3815
3816        // Modify the buffer
3817        buffer.update(&mut cx, |buffer, cx| {
3818            buffer.edit(vec![0..0], " ", cx);
3819            assert!(buffer.is_dirty());
3820            assert!(!buffer.has_conflict());
3821        });
3822
3823        // Change the file on disk again, adding blank lines to the beginning.
3824        fs::write(&abs_path, "\n\n\nAAAA\naaa\nBB\nbbbbb\n").unwrap();
3825
3826        // Because the buffer is modified, it doesn't reload from disk, but is
3827        // marked as having a conflict.
3828        buffer
3829            .condition(&cx, |buffer, _| buffer.has_conflict())
3830            .await;
3831    }
3832
3833    #[gpui::test]
3834    async fn test_grouped_diagnostics(mut cx: gpui::TestAppContext) {
3835        let fs = Arc::new(FakeFs::new(cx.background()));
3836        fs.insert_tree(
3837            "/the-dir",
3838            json!({
3839                "a.rs": "
3840                    fn foo(mut v: Vec<usize>) {
3841                        for x in &v {
3842                            v.push(1);
3843                        }
3844                    }
3845                "
3846                .unindent(),
3847            }),
3848        )
3849        .await;
3850
3851        let project = Project::test(fs.clone(), &mut cx);
3852        let (worktree, _) = project
3853            .update(&mut cx, |p, cx| {
3854                p.find_or_create_local_worktree("/the-dir", false, cx)
3855            })
3856            .await
3857            .unwrap();
3858        let worktree_id = worktree.read_with(&cx, |tree, _| tree.id());
3859
3860        let buffer = project
3861            .update(&mut cx, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
3862            .await
3863            .unwrap();
3864
3865        let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
3866        let message = lsp::PublishDiagnosticsParams {
3867            uri: buffer_uri.clone(),
3868            diagnostics: vec![
3869                lsp::Diagnostic {
3870                    range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3871                    severity: Some(DiagnosticSeverity::WARNING),
3872                    message: "error 1".to_string(),
3873                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3874                        location: lsp::Location {
3875                            uri: buffer_uri.clone(),
3876                            range: lsp::Range::new(
3877                                lsp::Position::new(1, 8),
3878                                lsp::Position::new(1, 9),
3879                            ),
3880                        },
3881                        message: "error 1 hint 1".to_string(),
3882                    }]),
3883                    ..Default::default()
3884                },
3885                lsp::Diagnostic {
3886                    range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
3887                    severity: Some(DiagnosticSeverity::HINT),
3888                    message: "error 1 hint 1".to_string(),
3889                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3890                        location: lsp::Location {
3891                            uri: buffer_uri.clone(),
3892                            range: lsp::Range::new(
3893                                lsp::Position::new(1, 8),
3894                                lsp::Position::new(1, 9),
3895                            ),
3896                        },
3897                        message: "original diagnostic".to_string(),
3898                    }]),
3899                    ..Default::default()
3900                },
3901                lsp::Diagnostic {
3902                    range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
3903                    severity: Some(DiagnosticSeverity::ERROR),
3904                    message: "error 2".to_string(),
3905                    related_information: Some(vec![
3906                        lsp::DiagnosticRelatedInformation {
3907                            location: lsp::Location {
3908                                uri: buffer_uri.clone(),
3909                                range: lsp::Range::new(
3910                                    lsp::Position::new(1, 13),
3911                                    lsp::Position::new(1, 15),
3912                                ),
3913                            },
3914                            message: "error 2 hint 1".to_string(),
3915                        },
3916                        lsp::DiagnosticRelatedInformation {
3917                            location: lsp::Location {
3918                                uri: buffer_uri.clone(),
3919                                range: lsp::Range::new(
3920                                    lsp::Position::new(1, 13),
3921                                    lsp::Position::new(1, 15),
3922                                ),
3923                            },
3924                            message: "error 2 hint 2".to_string(),
3925                        },
3926                    ]),
3927                    ..Default::default()
3928                },
3929                lsp::Diagnostic {
3930                    range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
3931                    severity: Some(DiagnosticSeverity::HINT),
3932                    message: "error 2 hint 1".to_string(),
3933                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3934                        location: lsp::Location {
3935                            uri: buffer_uri.clone(),
3936                            range: lsp::Range::new(
3937                                lsp::Position::new(2, 8),
3938                                lsp::Position::new(2, 17),
3939                            ),
3940                        },
3941                        message: "original diagnostic".to_string(),
3942                    }]),
3943                    ..Default::default()
3944                },
3945                lsp::Diagnostic {
3946                    range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
3947                    severity: Some(DiagnosticSeverity::HINT),
3948                    message: "error 2 hint 2".to_string(),
3949                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
3950                        location: lsp::Location {
3951                            uri: buffer_uri.clone(),
3952                            range: lsp::Range::new(
3953                                lsp::Position::new(2, 8),
3954                                lsp::Position::new(2, 17),
3955                            ),
3956                        },
3957                        message: "original diagnostic".to_string(),
3958                    }]),
3959                    ..Default::default()
3960                },
3961            ],
3962            version: None,
3963        };
3964
3965        project
3966            .update(&mut cx, |p, cx| {
3967                p.update_diagnostics(message, &Default::default(), cx)
3968            })
3969            .unwrap();
3970        let buffer = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3971
3972        assert_eq!(
3973            buffer
3974                .diagnostics_in_range::<_, Point>(0..buffer.len())
3975                .collect::<Vec<_>>(),
3976            &[
3977                DiagnosticEntry {
3978                    range: Point::new(1, 8)..Point::new(1, 9),
3979                    diagnostic: Diagnostic {
3980                        severity: DiagnosticSeverity::WARNING,
3981                        message: "error 1".to_string(),
3982                        group_id: 0,
3983                        is_primary: true,
3984                        ..Default::default()
3985                    }
3986                },
3987                DiagnosticEntry {
3988                    range: Point::new(1, 8)..Point::new(1, 9),
3989                    diagnostic: Diagnostic {
3990                        severity: DiagnosticSeverity::HINT,
3991                        message: "error 1 hint 1".to_string(),
3992                        group_id: 0,
3993                        is_primary: false,
3994                        ..Default::default()
3995                    }
3996                },
3997                DiagnosticEntry {
3998                    range: Point::new(1, 13)..Point::new(1, 15),
3999                    diagnostic: Diagnostic {
4000                        severity: DiagnosticSeverity::HINT,
4001                        message: "error 2 hint 1".to_string(),
4002                        group_id: 1,
4003                        is_primary: false,
4004                        ..Default::default()
4005                    }
4006                },
4007                DiagnosticEntry {
4008                    range: Point::new(1, 13)..Point::new(1, 15),
4009                    diagnostic: Diagnostic {
4010                        severity: DiagnosticSeverity::HINT,
4011                        message: "error 2 hint 2".to_string(),
4012                        group_id: 1,
4013                        is_primary: false,
4014                        ..Default::default()
4015                    }
4016                },
4017                DiagnosticEntry {
4018                    range: Point::new(2, 8)..Point::new(2, 17),
4019                    diagnostic: Diagnostic {
4020                        severity: DiagnosticSeverity::ERROR,
4021                        message: "error 2".to_string(),
4022                        group_id: 1,
4023                        is_primary: true,
4024                        ..Default::default()
4025                    }
4026                }
4027            ]
4028        );
4029
4030        assert_eq!(
4031            buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
4032            &[
4033                DiagnosticEntry {
4034                    range: Point::new(1, 8)..Point::new(1, 9),
4035                    diagnostic: Diagnostic {
4036                        severity: DiagnosticSeverity::WARNING,
4037                        message: "error 1".to_string(),
4038                        group_id: 0,
4039                        is_primary: true,
4040                        ..Default::default()
4041                    }
4042                },
4043                DiagnosticEntry {
4044                    range: Point::new(1, 8)..Point::new(1, 9),
4045                    diagnostic: Diagnostic {
4046                        severity: DiagnosticSeverity::HINT,
4047                        message: "error 1 hint 1".to_string(),
4048                        group_id: 0,
4049                        is_primary: false,
4050                        ..Default::default()
4051                    }
4052                },
4053            ]
4054        );
4055        assert_eq!(
4056            buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
4057            &[
4058                DiagnosticEntry {
4059                    range: Point::new(1, 13)..Point::new(1, 15),
4060                    diagnostic: Diagnostic {
4061                        severity: DiagnosticSeverity::HINT,
4062                        message: "error 2 hint 1".to_string(),
4063                        group_id: 1,
4064                        is_primary: false,
4065                        ..Default::default()
4066                    }
4067                },
4068                DiagnosticEntry {
4069                    range: Point::new(1, 13)..Point::new(1, 15),
4070                    diagnostic: Diagnostic {
4071                        severity: DiagnosticSeverity::HINT,
4072                        message: "error 2 hint 2".to_string(),
4073                        group_id: 1,
4074                        is_primary: false,
4075                        ..Default::default()
4076                    }
4077                },
4078                DiagnosticEntry {
4079                    range: Point::new(2, 8)..Point::new(2, 17),
4080                    diagnostic: Diagnostic {
4081                        severity: DiagnosticSeverity::ERROR,
4082                        message: "error 2".to_string(),
4083                        group_id: 1,
4084                        is_primary: true,
4085                        ..Default::default()
4086                    }
4087                }
4088            ]
4089        );
4090    }
4091}