project.rs

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