project.rs

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