project.rs

   1mod ignore;
   2mod lsp_command;
   3pub mod search;
   4pub mod worktree;
   5
   6#[cfg(test)]
   7mod project_tests;
   8
   9use anyhow::{anyhow, Context, Result};
  10use client::{proto, Client, PeerId, TypedEnvelope, UserStore};
  11use clock::ReplicaId;
  12use collections::{hash_map, BTreeMap, HashMap, HashSet};
  13use futures::{
  14    channel::{mpsc, oneshot},
  15    future::Shared,
  16    AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
  17};
  18
  19use gpui::{
  20    AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
  21    MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
  22};
  23use language::{
  24    point_to_lsp,
  25    proto::{
  26        deserialize_anchor, deserialize_line_ending, deserialize_version, serialize_anchor,
  27        serialize_version,
  28    },
  29    range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CachedLspAdapter, CharKind, CodeAction,
  30    CodeLabel, Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Event as BufferEvent,
  31    File as _, Language, LanguageRegistry, LanguageServerName, LocalFile, OffsetRangeExt,
  32    Operation, Patch, PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction,
  33};
  34use lsp::{
  35    DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer, LanguageString,
  36    MarkedString,
  37};
  38use lsp_command::*;
  39use parking_lot::Mutex;
  40use postage::watch;
  41use rand::prelude::*;
  42use search::SearchQuery;
  43use serde::Serialize;
  44use settings::{FormatOnSave, Formatter, Settings};
  45use sha2::{Digest, Sha256};
  46use similar::{ChangeTag, TextDiff};
  47use std::{
  48    cell::RefCell,
  49    cmp::{self, Ordering},
  50    convert::TryInto,
  51    hash::Hash,
  52    mem,
  53    num::NonZeroU32,
  54    ops::Range,
  55    path::{Component, Path, PathBuf},
  56    rc::Rc,
  57    str,
  58    sync::{
  59        atomic::{AtomicUsize, Ordering::SeqCst},
  60        Arc,
  61    },
  62    time::Instant,
  63};
  64use thiserror::Error;
  65use util::{defer, post_inc, ResultExt, TryFutureExt as _};
  66
  67pub use db::Db;
  68pub use fs::*;
  69pub use worktree::*;
  70
  71pub trait Item: Entity {
  72    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  73}
  74
  75// Language server state is stored across 3 collections:
  76//     language_servers =>
  77//         a mapping from unique server id to LanguageServerState which can either be a task for a
  78//         server in the process of starting, or a running server with adapter and language server arcs
  79//     language_server_ids => a mapping from worktreeId and server name to the unique server id
  80//     language_server_statuses => a mapping from unique server id to the current server status
  81//
  82// Multiple worktrees can map to the same language server for example when you jump to the definition
  83// of a file in the standard library. So language_server_ids is used to look up which server is active
  84// for a given worktree and language server name
  85//
  86// When starting a language server, first the id map is checked to make sure a server isn't already available
  87// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
  88// the Starting variant of LanguageServerState is stored in the language_servers map.
  89pub struct Project {
  90    worktrees: Vec<WorktreeHandle>,
  91    active_entry: Option<ProjectEntryId>,
  92    languages: Arc<LanguageRegistry>,
  93    language_servers: HashMap<usize, LanguageServerState>,
  94    language_server_ids: HashMap<(WorktreeId, LanguageServerName), usize>,
  95    language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
  96    language_server_settings: Arc<Mutex<serde_json::Value>>,
  97    last_workspace_edits_by_language_server: HashMap<usize, ProjectTransaction>,
  98    next_language_server_id: usize,
  99    client: Arc<client::Client>,
 100    next_entry_id: Arc<AtomicUsize>,
 101    next_diagnostic_group_id: usize,
 102    user_store: ModelHandle<UserStore>,
 103    fs: Arc<dyn Fs>,
 104    client_state: Option<ProjectClientState>,
 105    collaborators: HashMap<PeerId, Collaborator>,
 106    client_subscriptions: Vec<client::Subscription>,
 107    _subscriptions: Vec<gpui::Subscription>,
 108    opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
 109    shared_buffers: HashMap<PeerId, HashSet<u64>>,
 110    #[allow(clippy::type_complexity)]
 111    loading_buffers: HashMap<
 112        ProjectPath,
 113        postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
 114    >,
 115    #[allow(clippy::type_complexity)]
 116    loading_local_worktrees:
 117        HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
 118    opened_buffers: HashMap<u64, OpenBuffer>,
 119    incomplete_buffers: HashMap<u64, ModelHandle<Buffer>>,
 120    buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
 121    buffers_being_formatted: HashSet<usize>,
 122    nonce: u128,
 123    _maintain_buffer_languages: Task<()>,
 124}
 125
 126#[derive(Error, Debug)]
 127pub enum JoinProjectError {
 128    #[error("host declined join request")]
 129    HostDeclined,
 130    #[error("host closed the project")]
 131    HostClosedProject,
 132    #[error("host went offline")]
 133    HostWentOffline,
 134    #[error("{0}")]
 135    Other(#[from] anyhow::Error),
 136}
 137
 138enum OpenBuffer {
 139    Strong(ModelHandle<Buffer>),
 140    Weak(WeakModelHandle<Buffer>),
 141    Operations(Vec<Operation>),
 142}
 143
 144enum WorktreeHandle {
 145    Strong(ModelHandle<Worktree>),
 146    Weak(WeakModelHandle<Worktree>),
 147}
 148
 149enum ProjectClientState {
 150    Local {
 151        remote_id: u64,
 152        metadata_changed: mpsc::UnboundedSender<oneshot::Sender<()>>,
 153        _maintain_metadata: Task<()>,
 154        _detect_unshare: Task<Option<()>>,
 155    },
 156    Remote {
 157        sharing_has_stopped: bool,
 158        remote_id: u64,
 159        replica_id: ReplicaId,
 160        _detect_unshare: Task<Option<()>>,
 161    },
 162}
 163
 164#[derive(Clone, Debug)]
 165pub struct Collaborator {
 166    pub peer_id: PeerId,
 167    pub replica_id: ReplicaId,
 168}
 169
 170#[derive(Clone, Debug, PartialEq, Eq)]
 171pub enum Event {
 172    ActiveEntryChanged(Option<ProjectEntryId>),
 173    WorktreeAdded,
 174    WorktreeRemoved(WorktreeId),
 175    DiskBasedDiagnosticsStarted {
 176        language_server_id: usize,
 177    },
 178    DiskBasedDiagnosticsFinished {
 179        language_server_id: usize,
 180    },
 181    DiagnosticsUpdated {
 182        path: ProjectPath,
 183        language_server_id: usize,
 184    },
 185    RemoteIdChanged(Option<u64>),
 186    DisconnectedFromHost,
 187    CollaboratorLeft(PeerId),
 188}
 189
 190pub enum LanguageServerState {
 191    Starting(Task<Option<Arc<LanguageServer>>>),
 192    Running {
 193        language: Arc<Language>,
 194        adapter: Arc<CachedLspAdapter>,
 195        server: Arc<LanguageServer>,
 196    },
 197}
 198
 199#[derive(Serialize)]
 200pub struct LanguageServerStatus {
 201    pub name: String,
 202    pub pending_work: BTreeMap<String, LanguageServerProgress>,
 203    pub has_pending_diagnostic_updates: bool,
 204    progress_tokens: HashSet<String>,
 205}
 206
 207#[derive(Clone, Debug, Serialize)]
 208pub struct LanguageServerProgress {
 209    pub message: Option<String>,
 210    pub percentage: Option<usize>,
 211    #[serde(skip_serializing)]
 212    pub last_update_at: Instant,
 213}
 214
 215#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 216pub struct ProjectPath {
 217    pub worktree_id: WorktreeId,
 218    pub path: Arc<Path>,
 219}
 220
 221#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 222pub struct DiagnosticSummary {
 223    pub language_server_id: usize,
 224    pub error_count: usize,
 225    pub warning_count: usize,
 226}
 227
 228#[derive(Debug, Clone)]
 229pub struct Location {
 230    pub buffer: ModelHandle<Buffer>,
 231    pub range: Range<language::Anchor>,
 232}
 233
 234#[derive(Debug, Clone)]
 235pub struct LocationLink {
 236    pub origin: Option<Location>,
 237    pub target: Location,
 238}
 239
 240#[derive(Debug)]
 241pub struct DocumentHighlight {
 242    pub range: Range<language::Anchor>,
 243    pub kind: DocumentHighlightKind,
 244}
 245
 246#[derive(Clone, Debug)]
 247pub struct Symbol {
 248    pub language_server_name: LanguageServerName,
 249    pub source_worktree_id: WorktreeId,
 250    pub path: ProjectPath,
 251    pub label: CodeLabel,
 252    pub name: String,
 253    pub kind: lsp::SymbolKind,
 254    pub range: Range<PointUtf16>,
 255    pub signature: [u8; 32],
 256}
 257
 258#[derive(Clone, Debug, PartialEq)]
 259pub struct HoverBlock {
 260    pub text: String,
 261    pub language: Option<String>,
 262}
 263
 264impl HoverBlock {
 265    fn try_new(marked_string: MarkedString) -> Option<Self> {
 266        let result = match marked_string {
 267            MarkedString::LanguageString(LanguageString { language, value }) => HoverBlock {
 268                text: value,
 269                language: Some(language),
 270            },
 271            MarkedString::String(text) => HoverBlock {
 272                text,
 273                language: None,
 274            },
 275        };
 276        if result.text.is_empty() {
 277            None
 278        } else {
 279            Some(result)
 280        }
 281    }
 282}
 283
 284#[derive(Debug)]
 285pub struct Hover {
 286    pub contents: Vec<HoverBlock>,
 287    pub range: Option<Range<language::Anchor>>,
 288}
 289
 290#[derive(Default)]
 291pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
 292
 293impl DiagnosticSummary {
 294    fn new<'a, T: 'a>(
 295        language_server_id: usize,
 296        diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>,
 297    ) -> Self {
 298        let mut this = Self {
 299            language_server_id,
 300            error_count: 0,
 301            warning_count: 0,
 302        };
 303
 304        for entry in diagnostics {
 305            if entry.diagnostic.is_primary {
 306                match entry.diagnostic.severity {
 307                    DiagnosticSeverity::ERROR => this.error_count += 1,
 308                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 309                    _ => {}
 310                }
 311            }
 312        }
 313
 314        this
 315    }
 316
 317    pub fn is_empty(&self) -> bool {
 318        self.error_count == 0 && self.warning_count == 0
 319    }
 320
 321    pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
 322        proto::DiagnosticSummary {
 323            path: path.to_string_lossy().to_string(),
 324            language_server_id: self.language_server_id as u64,
 325            error_count: self.error_count as u32,
 326            warning_count: self.warning_count as u32,
 327        }
 328    }
 329}
 330
 331#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
 332pub struct ProjectEntryId(usize);
 333
 334impl ProjectEntryId {
 335    pub const MAX: Self = Self(usize::MAX);
 336
 337    pub fn new(counter: &AtomicUsize) -> Self {
 338        Self(counter.fetch_add(1, SeqCst))
 339    }
 340
 341    pub fn from_proto(id: u64) -> Self {
 342        Self(id as usize)
 343    }
 344
 345    pub fn to_proto(&self) -> u64 {
 346        self.0 as u64
 347    }
 348
 349    pub fn to_usize(&self) -> usize {
 350        self.0
 351    }
 352}
 353
 354#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 355pub enum FormatTrigger {
 356    Save,
 357    Manual,
 358}
 359
 360impl FormatTrigger {
 361    fn from_proto(value: i32) -> FormatTrigger {
 362        match value {
 363            0 => FormatTrigger::Save,
 364            1 => FormatTrigger::Manual,
 365            _ => FormatTrigger::Save,
 366        }
 367    }
 368}
 369
 370impl Project {
 371    pub fn init(client: &Arc<Client>) {
 372        client.add_model_message_handler(Self::handle_add_collaborator);
 373        client.add_model_message_handler(Self::handle_buffer_reloaded);
 374        client.add_model_message_handler(Self::handle_buffer_saved);
 375        client.add_model_message_handler(Self::handle_start_language_server);
 376        client.add_model_message_handler(Self::handle_update_language_server);
 377        client.add_model_message_handler(Self::handle_remove_collaborator);
 378        client.add_model_message_handler(Self::handle_update_project);
 379        client.add_model_message_handler(Self::handle_unshare_project);
 380        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 381        client.add_model_message_handler(Self::handle_update_buffer_file);
 382        client.add_model_message_handler(Self::handle_update_buffer);
 383        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
 384        client.add_model_message_handler(Self::handle_update_worktree);
 385        client.add_model_request_handler(Self::handle_create_project_entry);
 386        client.add_model_request_handler(Self::handle_rename_project_entry);
 387        client.add_model_request_handler(Self::handle_copy_project_entry);
 388        client.add_model_request_handler(Self::handle_delete_project_entry);
 389        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
 390        client.add_model_request_handler(Self::handle_apply_code_action);
 391        client.add_model_request_handler(Self::handle_reload_buffers);
 392        client.add_model_request_handler(Self::handle_format_buffers);
 393        client.add_model_request_handler(Self::handle_get_code_actions);
 394        client.add_model_request_handler(Self::handle_get_completions);
 395        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
 396        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
 397        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
 398        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 399        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
 400        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
 401        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
 402        client.add_model_request_handler(Self::handle_search_project);
 403        client.add_model_request_handler(Self::handle_get_project_symbols);
 404        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
 405        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 406        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 407        client.add_model_request_handler(Self::handle_save_buffer);
 408        client.add_model_message_handler(Self::handle_update_diff_base);
 409    }
 410
 411    pub fn local(
 412        client: Arc<Client>,
 413        user_store: ModelHandle<UserStore>,
 414        languages: Arc<LanguageRegistry>,
 415        fs: Arc<dyn Fs>,
 416        cx: &mut MutableAppContext,
 417    ) -> ModelHandle<Self> {
 418        cx.add_model(|cx: &mut ModelContext<Self>| Self {
 419            worktrees: Default::default(),
 420            collaborators: Default::default(),
 421            opened_buffers: Default::default(),
 422            shared_buffers: Default::default(),
 423            incomplete_buffers: Default::default(),
 424            loading_buffers: Default::default(),
 425            loading_local_worktrees: Default::default(),
 426            buffer_snapshots: Default::default(),
 427            client_state: None,
 428            opened_buffer: watch::channel(),
 429            client_subscriptions: Vec::new(),
 430            _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
 431            _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
 432            active_entry: None,
 433            languages,
 434            client,
 435            user_store,
 436            fs,
 437            next_entry_id: Default::default(),
 438            next_diagnostic_group_id: Default::default(),
 439            language_servers: Default::default(),
 440            language_server_ids: Default::default(),
 441            language_server_statuses: Default::default(),
 442            last_workspace_edits_by_language_server: Default::default(),
 443            language_server_settings: Default::default(),
 444            buffers_being_formatted: Default::default(),
 445            next_language_server_id: 0,
 446            nonce: StdRng::from_entropy().gen(),
 447        })
 448    }
 449
 450    pub async fn remote(
 451        remote_id: u64,
 452        client: Arc<Client>,
 453        user_store: ModelHandle<UserStore>,
 454        languages: Arc<LanguageRegistry>,
 455        fs: Arc<dyn Fs>,
 456        mut cx: AsyncAppContext,
 457    ) -> Result<ModelHandle<Self>, JoinProjectError> {
 458        client.authenticate_and_connect(true, &cx).await?;
 459
 460        let subscription = client.subscribe_to_entity(remote_id);
 461        let response = client
 462            .request(proto::JoinProject {
 463                project_id: remote_id,
 464            })
 465            .await?;
 466        let this = cx.add_model(|cx| {
 467            let replica_id = response.replica_id as ReplicaId;
 468
 469            let mut worktrees = Vec::new();
 470            for worktree in response.worktrees {
 471                let worktree = cx.update(|cx| {
 472                    Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx)
 473                });
 474                worktrees.push(worktree);
 475            }
 476
 477            let mut this = Self {
 478                worktrees: Vec::new(),
 479                loading_buffers: Default::default(),
 480                opened_buffer: watch::channel(),
 481                shared_buffers: Default::default(),
 482                incomplete_buffers: Default::default(),
 483                loading_local_worktrees: Default::default(),
 484                active_entry: None,
 485                collaborators: Default::default(),
 486                _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
 487                languages,
 488                user_store: user_store.clone(),
 489                fs,
 490                next_entry_id: Default::default(),
 491                next_diagnostic_group_id: Default::default(),
 492                client_subscriptions: Default::default(),
 493                _subscriptions: Default::default(),
 494                client: client.clone(),
 495                client_state: Some(ProjectClientState::Remote {
 496                    sharing_has_stopped: false,
 497                    remote_id,
 498                    replica_id,
 499                    _detect_unshare: cx.spawn_weak(move |this, mut cx| {
 500                        async move {
 501                            let mut status = client.status();
 502                            let is_connected =
 503                                status.next().await.map_or(false, |s| s.is_connected());
 504                            // Even if we're initially connected, any future change of the status means we momentarily disconnected.
 505                            if !is_connected || status.next().await.is_some() {
 506                                if let Some(this) = this.upgrade(&cx) {
 507                                    this.update(&mut cx, |this, cx| this.disconnected_from_host(cx))
 508                                }
 509                            }
 510                            Ok(())
 511                        }
 512                        .log_err()
 513                    }),
 514                }),
 515                language_servers: Default::default(),
 516                language_server_ids: Default::default(),
 517                language_server_settings: Default::default(),
 518                language_server_statuses: response
 519                    .language_servers
 520                    .into_iter()
 521                    .map(|server| {
 522                        (
 523                            server.id as usize,
 524                            LanguageServerStatus {
 525                                name: server.name,
 526                                pending_work: Default::default(),
 527                                has_pending_diagnostic_updates: false,
 528                                progress_tokens: Default::default(),
 529                            },
 530                        )
 531                    })
 532                    .collect(),
 533                last_workspace_edits_by_language_server: Default::default(),
 534                next_language_server_id: 0,
 535                opened_buffers: Default::default(),
 536                buffers_being_formatted: Default::default(),
 537                buffer_snapshots: Default::default(),
 538                nonce: StdRng::from_entropy().gen(),
 539            };
 540            for worktree in worktrees {
 541                let _ = this.add_worktree(&worktree, cx);
 542            }
 543            this
 544        });
 545        let subscription = subscription.set_model(&this, &mut cx);
 546
 547        let user_ids = response
 548            .collaborators
 549            .iter()
 550            .map(|peer| peer.user_id)
 551            .collect();
 552        user_store
 553            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
 554            .await?;
 555        let mut collaborators = HashMap::default();
 556        for message in response.collaborators {
 557            let collaborator = Collaborator::from_proto(message);
 558            collaborators.insert(collaborator.peer_id, collaborator);
 559        }
 560
 561        this.update(&mut cx, |this, _| {
 562            this.collaborators = collaborators;
 563            this.client_subscriptions.push(subscription);
 564        });
 565
 566        Ok(this)
 567    }
 568
 569    #[cfg(any(test, feature = "test-support"))]
 570    pub async fn test(
 571        fs: Arc<dyn Fs>,
 572        root_paths: impl IntoIterator<Item = &Path>,
 573        cx: &mut gpui::TestAppContext,
 574    ) -> ModelHandle<Project> {
 575        if !cx.read(|cx| cx.has_global::<Settings>()) {
 576            cx.update(|cx| {
 577                cx.set_global(Settings::test(cx));
 578                cx.set_global(HomeDir(Path::new("/tmp/").to_path_buf()))
 579            });
 580        }
 581
 582        let languages = Arc::new(LanguageRegistry::test());
 583        let http_client = client::test::FakeHttpClient::with_404_response();
 584        let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
 585        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 586        let project = cx.update(|cx| Project::local(client, user_store, languages, fs, cx));
 587        for path in root_paths {
 588            let (tree, _) = project
 589                .update(cx, |project, cx| {
 590                    project.find_or_create_local_worktree(path, true, cx)
 591                })
 592                .await
 593                .unwrap();
 594            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 595                .await;
 596        }
 597        project
 598    }
 599
 600    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 601        let settings = cx.global::<Settings>();
 602
 603        let mut language_servers_to_start = Vec::new();
 604        for buffer in self.opened_buffers.values() {
 605            if let Some(buffer) = buffer.upgrade(cx) {
 606                let buffer = buffer.read(cx);
 607                if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
 608                {
 609                    if settings.enable_language_server(Some(&language.name())) {
 610                        let worktree = file.worktree.read(cx);
 611                        language_servers_to_start.push((
 612                            worktree.id(),
 613                            worktree.as_local().unwrap().abs_path().clone(),
 614                            language.clone(),
 615                        ));
 616                    }
 617                }
 618            }
 619        }
 620
 621        let mut language_servers_to_stop = Vec::new();
 622        for language in self.languages.to_vec() {
 623            if let Some(lsp_adapter) = language.lsp_adapter() {
 624                if !settings.enable_language_server(Some(&language.name())) {
 625                    let lsp_name = &lsp_adapter.name;
 626                    for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 627                        if lsp_name == started_lsp_name {
 628                            language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 629                        }
 630                    }
 631                }
 632            }
 633        }
 634
 635        // Stop all newly-disabled language servers.
 636        for (worktree_id, adapter_name) in language_servers_to_stop {
 637            self.stop_language_server(worktree_id, adapter_name, cx)
 638                .detach();
 639        }
 640
 641        // Start all the newly-enabled language servers.
 642        for (worktree_id, worktree_path, language) in language_servers_to_start {
 643            self.start_language_server(worktree_id, worktree_path, language, cx);
 644        }
 645
 646        cx.notify();
 647    }
 648
 649    pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
 650        self.opened_buffers
 651            .get(&remote_id)
 652            .and_then(|buffer| buffer.upgrade(cx))
 653    }
 654
 655    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 656        &self.languages
 657    }
 658
 659    pub fn client(&self) -> Arc<Client> {
 660        self.client.clone()
 661    }
 662
 663    pub fn user_store(&self) -> ModelHandle<UserStore> {
 664        self.user_store.clone()
 665    }
 666
 667    #[cfg(any(test, feature = "test-support"))]
 668    pub fn check_invariants(&self, cx: &AppContext) {
 669        if self.is_local() {
 670            let mut worktree_root_paths = HashMap::default();
 671            for worktree in self.worktrees(cx) {
 672                let worktree = worktree.read(cx);
 673                let abs_path = worktree.as_local().unwrap().abs_path().clone();
 674                let prev_worktree_id = worktree_root_paths.insert(abs_path.clone(), worktree.id());
 675                assert_eq!(
 676                    prev_worktree_id,
 677                    None,
 678                    "abs path {:?} for worktree {:?} is not unique ({:?} was already registered with the same path)",
 679                    abs_path,
 680                    worktree.id(),
 681                    prev_worktree_id
 682                )
 683            }
 684        } else {
 685            let replica_id = self.replica_id();
 686            for buffer in self.opened_buffers.values() {
 687                if let Some(buffer) = buffer.upgrade(cx) {
 688                    let buffer = buffer.read(cx);
 689                    assert_eq!(
 690                        buffer.deferred_ops_len(),
 691                        0,
 692                        "replica {}, buffer {} has deferred operations",
 693                        replica_id,
 694                        buffer.remote_id()
 695                    );
 696                }
 697            }
 698        }
 699    }
 700
 701    #[cfg(any(test, feature = "test-support"))]
 702    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 703        let path = path.into();
 704        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 705            self.opened_buffers.iter().any(|(_, buffer)| {
 706                if let Some(buffer) = buffer.upgrade(cx) {
 707                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 708                        if file.worktree == worktree && file.path() == &path.path {
 709                            return true;
 710                        }
 711                    }
 712                }
 713                false
 714            })
 715        } else {
 716            false
 717        }
 718    }
 719
 720    pub fn fs(&self) -> &Arc<dyn Fs> {
 721        &self.fs
 722    }
 723
 724    pub fn remote_id(&self) -> Option<u64> {
 725        match self.client_state.as_ref()? {
 726            ProjectClientState::Local { remote_id, .. }
 727            | ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
 728        }
 729    }
 730
 731    pub fn replica_id(&self) -> ReplicaId {
 732        match &self.client_state {
 733            Some(ProjectClientState::Remote { replica_id, .. }) => *replica_id,
 734            _ => 0,
 735        }
 736    }
 737
 738    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) -> impl Future<Output = ()> {
 739        let (tx, rx) = oneshot::channel();
 740        if let Some(ProjectClientState::Local {
 741            metadata_changed, ..
 742        }) = &mut self.client_state
 743        {
 744            let _ = metadata_changed.unbounded_send(tx);
 745        }
 746        cx.notify();
 747
 748        async move {
 749            // If the project is shared, this will resolve when the `_maintain_metadata` task has
 750            // a chance to update the metadata. Otherwise, it will resolve right away because `tx`
 751            // will get dropped.
 752            let _ = rx.await;
 753        }
 754    }
 755
 756    pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
 757        &self.collaborators
 758    }
 759
 760    pub fn worktrees<'a>(
 761        &'a self,
 762        cx: &'a AppContext,
 763    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
 764        self.worktrees
 765            .iter()
 766            .filter_map(move |worktree| worktree.upgrade(cx))
 767    }
 768
 769    pub fn visible_worktrees<'a>(
 770        &'a self,
 771        cx: &'a AppContext,
 772    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
 773        self.worktrees.iter().filter_map(|worktree| {
 774            worktree.upgrade(cx).and_then(|worktree| {
 775                if worktree.read(cx).is_visible() {
 776                    Some(worktree)
 777                } else {
 778                    None
 779                }
 780            })
 781        })
 782    }
 783
 784    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
 785        self.visible_worktrees(cx)
 786            .map(|tree| tree.read(cx).root_name())
 787    }
 788
 789    pub fn worktree_for_id(
 790        &self,
 791        id: WorktreeId,
 792        cx: &AppContext,
 793    ) -> Option<ModelHandle<Worktree>> {
 794        self.worktrees(cx)
 795            .find(|worktree| worktree.read(cx).id() == id)
 796    }
 797
 798    pub fn worktree_for_entry(
 799        &self,
 800        entry_id: ProjectEntryId,
 801        cx: &AppContext,
 802    ) -> Option<ModelHandle<Worktree>> {
 803        self.worktrees(cx)
 804            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
 805    }
 806
 807    pub fn worktree_id_for_entry(
 808        &self,
 809        entry_id: ProjectEntryId,
 810        cx: &AppContext,
 811    ) -> Option<WorktreeId> {
 812        self.worktree_for_entry(entry_id, cx)
 813            .map(|worktree| worktree.read(cx).id())
 814    }
 815
 816    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
 817        paths.iter().all(|path| self.contains_path(path, cx))
 818    }
 819
 820    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
 821        for worktree in self.worktrees(cx) {
 822            let worktree = worktree.read(cx).as_local();
 823            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
 824                return true;
 825            }
 826        }
 827        false
 828    }
 829
 830    pub fn create_entry(
 831        &mut self,
 832        project_path: impl Into<ProjectPath>,
 833        is_directory: bool,
 834        cx: &mut ModelContext<Self>,
 835    ) -> Option<Task<Result<Entry>>> {
 836        let project_path = project_path.into();
 837        let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 838        if self.is_local() {
 839            Some(worktree.update(cx, |worktree, cx| {
 840                worktree
 841                    .as_local_mut()
 842                    .unwrap()
 843                    .create_entry(project_path.path, is_directory, cx)
 844            }))
 845        } else {
 846            let client = self.client.clone();
 847            let project_id = self.remote_id().unwrap();
 848            Some(cx.spawn_weak(|_, mut cx| async move {
 849                let response = client
 850                    .request(proto::CreateProjectEntry {
 851                        worktree_id: project_path.worktree_id.to_proto(),
 852                        project_id,
 853                        path: project_path.path.to_string_lossy().into(),
 854                        is_directory,
 855                    })
 856                    .await?;
 857                let entry = response
 858                    .entry
 859                    .ok_or_else(|| anyhow!("missing entry in response"))?;
 860                worktree
 861                    .update(&mut cx, |worktree, cx| {
 862                        worktree.as_remote_mut().unwrap().insert_entry(
 863                            entry,
 864                            response.worktree_scan_id as usize,
 865                            cx,
 866                        )
 867                    })
 868                    .await
 869            }))
 870        }
 871    }
 872
 873    pub fn copy_entry(
 874        &mut self,
 875        entry_id: ProjectEntryId,
 876        new_path: impl Into<Arc<Path>>,
 877        cx: &mut ModelContext<Self>,
 878    ) -> Option<Task<Result<Entry>>> {
 879        let worktree = self.worktree_for_entry(entry_id, cx)?;
 880        let new_path = new_path.into();
 881        if self.is_local() {
 882            worktree.update(cx, |worktree, cx| {
 883                worktree
 884                    .as_local_mut()
 885                    .unwrap()
 886                    .copy_entry(entry_id, new_path, cx)
 887            })
 888        } else {
 889            let client = self.client.clone();
 890            let project_id = self.remote_id().unwrap();
 891
 892            Some(cx.spawn_weak(|_, mut cx| async move {
 893                let response = client
 894                    .request(proto::CopyProjectEntry {
 895                        project_id,
 896                        entry_id: entry_id.to_proto(),
 897                        new_path: new_path.to_string_lossy().into(),
 898                    })
 899                    .await?;
 900                let entry = response
 901                    .entry
 902                    .ok_or_else(|| anyhow!("missing entry in response"))?;
 903                worktree
 904                    .update(&mut cx, |worktree, cx| {
 905                        worktree.as_remote_mut().unwrap().insert_entry(
 906                            entry,
 907                            response.worktree_scan_id as usize,
 908                            cx,
 909                        )
 910                    })
 911                    .await
 912            }))
 913        }
 914    }
 915
 916    pub fn rename_entry(
 917        &mut self,
 918        entry_id: ProjectEntryId,
 919        new_path: impl Into<Arc<Path>>,
 920        cx: &mut ModelContext<Self>,
 921    ) -> Option<Task<Result<Entry>>> {
 922        let worktree = self.worktree_for_entry(entry_id, cx)?;
 923        let new_path = new_path.into();
 924        if self.is_local() {
 925            worktree.update(cx, |worktree, cx| {
 926                worktree
 927                    .as_local_mut()
 928                    .unwrap()
 929                    .rename_entry(entry_id, new_path, cx)
 930            })
 931        } else {
 932            let client = self.client.clone();
 933            let project_id = self.remote_id().unwrap();
 934
 935            Some(cx.spawn_weak(|_, mut cx| async move {
 936                let response = client
 937                    .request(proto::RenameProjectEntry {
 938                        project_id,
 939                        entry_id: entry_id.to_proto(),
 940                        new_path: new_path.to_string_lossy().into(),
 941                    })
 942                    .await?;
 943                let entry = response
 944                    .entry
 945                    .ok_or_else(|| anyhow!("missing entry in response"))?;
 946                worktree
 947                    .update(&mut cx, |worktree, cx| {
 948                        worktree.as_remote_mut().unwrap().insert_entry(
 949                            entry,
 950                            response.worktree_scan_id as usize,
 951                            cx,
 952                        )
 953                    })
 954                    .await
 955            }))
 956        }
 957    }
 958
 959    pub fn delete_entry(
 960        &mut self,
 961        entry_id: ProjectEntryId,
 962        cx: &mut ModelContext<Self>,
 963    ) -> Option<Task<Result<()>>> {
 964        let worktree = self.worktree_for_entry(entry_id, cx)?;
 965        if self.is_local() {
 966            worktree.update(cx, |worktree, cx| {
 967                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
 968            })
 969        } else {
 970            let client = self.client.clone();
 971            let project_id = self.remote_id().unwrap();
 972            Some(cx.spawn_weak(|_, mut cx| async move {
 973                let response = client
 974                    .request(proto::DeleteProjectEntry {
 975                        project_id,
 976                        entry_id: entry_id.to_proto(),
 977                    })
 978                    .await?;
 979                worktree
 980                    .update(&mut cx, move |worktree, cx| {
 981                        worktree.as_remote_mut().unwrap().delete_entry(
 982                            entry_id,
 983                            response.worktree_scan_id as usize,
 984                            cx,
 985                        )
 986                    })
 987                    .await
 988            }))
 989        }
 990    }
 991
 992    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 993        if self.client_state.is_some() {
 994            return Task::ready(Err(anyhow!("project was already shared")));
 995        }
 996
 997        let mut worktree_share_tasks = Vec::new();
 998
 999        for open_buffer in self.opened_buffers.values_mut() {
1000            match open_buffer {
1001                OpenBuffer::Strong(_) => {}
1002                OpenBuffer::Weak(buffer) => {
1003                    if let Some(buffer) = buffer.upgrade(cx) {
1004                        *open_buffer = OpenBuffer::Strong(buffer);
1005                    }
1006                }
1007                OpenBuffer::Operations(_) => unreachable!(),
1008            }
1009        }
1010
1011        for worktree_handle in self.worktrees.iter_mut() {
1012            match worktree_handle {
1013                WorktreeHandle::Strong(_) => {}
1014                WorktreeHandle::Weak(worktree) => {
1015                    if let Some(worktree) = worktree.upgrade(cx) {
1016                        *worktree_handle = WorktreeHandle::Strong(worktree);
1017                    }
1018                }
1019            }
1020        }
1021
1022        for (server_id, status) in &self.language_server_statuses {
1023            self.client
1024                .send(proto::StartLanguageServer {
1025                    project_id,
1026                    server: Some(proto::LanguageServer {
1027                        id: *server_id as u64,
1028                        name: status.name.clone(),
1029                    }),
1030                })
1031                .log_err();
1032        }
1033
1034        for worktree in self.worktrees(cx).collect::<Vec<_>>() {
1035            worktree.update(cx, |worktree, cx| {
1036                let worktree = worktree.as_local_mut().unwrap();
1037                worktree_share_tasks.push(worktree.share(project_id, cx));
1038            });
1039        }
1040
1041        self.client_subscriptions.push(
1042            self.client
1043                .subscribe_to_entity(project_id)
1044                .set_model(&cx.handle(), &mut cx.to_async()),
1045        );
1046        let _ = self.metadata_changed(cx);
1047        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1048        cx.notify();
1049
1050        let mut status = self.client.status();
1051        let (metadata_changed_tx, mut metadata_changed_rx) = mpsc::unbounded();
1052        self.client_state = Some(ProjectClientState::Local {
1053            remote_id: project_id,
1054            metadata_changed: metadata_changed_tx,
1055            _maintain_metadata: cx.spawn_weak(move |this, cx| async move {
1056                while let Some(tx) = metadata_changed_rx.next().await {
1057                    let mut txs = vec![tx];
1058                    while let Ok(Some(next_tx)) = metadata_changed_rx.try_next() {
1059                        txs.push(next_tx);
1060                    }
1061
1062                    let Some(this) = this.upgrade(&cx) else { break };
1063                    this.read_with(&cx, |this, cx| {
1064                        let worktrees = this
1065                            .worktrees
1066                            .iter()
1067                            .filter_map(|worktree| {
1068                                worktree.upgrade(cx).map(|worktree| {
1069                                    worktree.read(cx).as_local().unwrap().metadata_proto()
1070                                })
1071                            })
1072                            .collect();
1073                        this.client.request(proto::UpdateProject {
1074                            project_id,
1075                            worktrees,
1076                        })
1077                    })
1078                    .await
1079                    .log_err();
1080
1081                    for tx in txs {
1082                        let _ = tx.send(());
1083                    }
1084                }
1085            }),
1086            _detect_unshare: cx.spawn_weak(move |this, mut cx| {
1087                async move {
1088                    let is_connected = status.next().await.map_or(false, |s| s.is_connected());
1089                    // Even if we're initially connected, any future change of the status means we momentarily disconnected.
1090                    if !is_connected || status.next().await.is_some() {
1091                        if let Some(this) = this.upgrade(&cx) {
1092                            let _ = this.update(&mut cx, |this, cx| this.unshare(cx));
1093                        }
1094                    }
1095                    Ok(())
1096                }
1097                .log_err()
1098            }),
1099        });
1100
1101        cx.foreground().spawn(async move {
1102            futures::future::try_join_all(worktree_share_tasks).await?;
1103            Ok(())
1104        })
1105    }
1106
1107    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1108        if self.is_remote() {
1109            return Err(anyhow!("attempted to unshare a remote project"));
1110        }
1111
1112        if let Some(ProjectClientState::Local { remote_id, .. }) = self.client_state.take() {
1113            self.collaborators.clear();
1114            self.shared_buffers.clear();
1115            self.client_subscriptions.clear();
1116
1117            for worktree_handle in self.worktrees.iter_mut() {
1118                if let WorktreeHandle::Strong(worktree) = worktree_handle {
1119                    let is_visible = worktree.update(cx, |worktree, _| {
1120                        worktree.as_local_mut().unwrap().unshare();
1121                        worktree.is_visible()
1122                    });
1123                    if !is_visible {
1124                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1125                    }
1126                }
1127            }
1128
1129            for open_buffer in self.opened_buffers.values_mut() {
1130                if let OpenBuffer::Strong(buffer) = open_buffer {
1131                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1132                }
1133            }
1134
1135            let _ = self.metadata_changed(cx);
1136            cx.notify();
1137            self.client.send(proto::UnshareProject {
1138                project_id: remote_id,
1139            })?;
1140
1141            Ok(())
1142        } else {
1143            Err(anyhow!("attempted to unshare an unshared project"))
1144        }
1145    }
1146
1147    fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1148        if let Some(ProjectClientState::Remote {
1149            sharing_has_stopped,
1150            ..
1151        }) = &mut self.client_state
1152        {
1153            *sharing_has_stopped = true;
1154            self.collaborators.clear();
1155            for worktree in &self.worktrees {
1156                if let Some(worktree) = worktree.upgrade(cx) {
1157                    worktree.update(cx, |worktree, _| {
1158                        if let Some(worktree) = worktree.as_remote_mut() {
1159                            worktree.disconnected_from_host();
1160                        }
1161                    });
1162                }
1163            }
1164            cx.emit(Event::DisconnectedFromHost);
1165            cx.notify();
1166
1167            // Wake up all futures currently waiting on a buffer to get opened,
1168            // to give them a chance to fail now that we've disconnected.
1169            *self.opened_buffer.0.borrow_mut() = ();
1170        }
1171    }
1172
1173    pub fn is_read_only(&self) -> bool {
1174        match &self.client_state {
1175            Some(ProjectClientState::Remote {
1176                sharing_has_stopped,
1177                ..
1178            }) => *sharing_has_stopped,
1179            _ => false,
1180        }
1181    }
1182
1183    pub fn is_local(&self) -> bool {
1184        match &self.client_state {
1185            Some(ProjectClientState::Remote { .. }) => false,
1186            _ => true,
1187        }
1188    }
1189
1190    pub fn is_remote(&self) -> bool {
1191        !self.is_local()
1192    }
1193
1194    pub fn create_buffer(
1195        &mut self,
1196        text: &str,
1197        language: Option<Arc<Language>>,
1198        cx: &mut ModelContext<Self>,
1199    ) -> Result<ModelHandle<Buffer>> {
1200        if self.is_remote() {
1201            return Err(anyhow!("creating buffers as a guest is not supported yet"));
1202        }
1203
1204        let buffer = cx.add_model(|cx| {
1205            Buffer::new(self.replica_id(), text, cx)
1206                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1207        });
1208        self.register_buffer(&buffer, cx)?;
1209        Ok(buffer)
1210    }
1211
1212    pub fn open_path(
1213        &mut self,
1214        path: impl Into<ProjectPath>,
1215        cx: &mut ModelContext<Self>,
1216    ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1217        let task = self.open_buffer(path, cx);
1218        cx.spawn_weak(|_, cx| async move {
1219            let buffer = task.await?;
1220            let project_entry_id = buffer
1221                .read_with(&cx, |buffer, cx| {
1222                    File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1223                })
1224                .ok_or_else(|| anyhow!("no project entry"))?;
1225            Ok((project_entry_id, buffer.into()))
1226        })
1227    }
1228
1229    pub fn open_local_buffer(
1230        &mut self,
1231        abs_path: impl AsRef<Path>,
1232        cx: &mut ModelContext<Self>,
1233    ) -> Task<Result<ModelHandle<Buffer>>> {
1234        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1235            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1236        } else {
1237            Task::ready(Err(anyhow!("no such path")))
1238        }
1239    }
1240
1241    pub fn open_buffer(
1242        &mut self,
1243        path: impl Into<ProjectPath>,
1244        cx: &mut ModelContext<Self>,
1245    ) -> Task<Result<ModelHandle<Buffer>>> {
1246        let project_path = path.into();
1247        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1248            worktree
1249        } else {
1250            return Task::ready(Err(anyhow!("no such worktree")));
1251        };
1252
1253        // If there is already a buffer for the given path, then return it.
1254        let existing_buffer = self.get_open_buffer(&project_path, cx);
1255        if let Some(existing_buffer) = existing_buffer {
1256            return Task::ready(Ok(existing_buffer));
1257        }
1258
1259        let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
1260            // If the given path is already being loaded, then wait for that existing
1261            // task to complete and return the same buffer.
1262            hash_map::Entry::Occupied(e) => e.get().clone(),
1263
1264            // Otherwise, record the fact that this path is now being loaded.
1265            hash_map::Entry::Vacant(entry) => {
1266                let (mut tx, rx) = postage::watch::channel();
1267                entry.insert(rx.clone());
1268
1269                let load_buffer = if worktree.read(cx).is_local() {
1270                    self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1271                } else {
1272                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1273                };
1274
1275                cx.spawn(move |this, mut cx| async move {
1276                    let load_result = load_buffer.await;
1277                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1278                        // Record the fact that the buffer is no longer loading.
1279                        this.loading_buffers.remove(&project_path);
1280                        let buffer = load_result.map_err(Arc::new)?;
1281                        Ok(buffer)
1282                    }));
1283                })
1284                .detach();
1285                rx
1286            }
1287        };
1288
1289        cx.foreground().spawn(async move {
1290            loop {
1291                if let Some(result) = loading_watch.borrow().as_ref() {
1292                    match result {
1293                        Ok(buffer) => return Ok(buffer.clone()),
1294                        Err(error) => return Err(anyhow!("{}", error)),
1295                    }
1296                }
1297                loading_watch.next().await;
1298            }
1299        })
1300    }
1301
1302    fn open_local_buffer_internal(
1303        &mut self,
1304        path: &Arc<Path>,
1305        worktree: &ModelHandle<Worktree>,
1306        cx: &mut ModelContext<Self>,
1307    ) -> Task<Result<ModelHandle<Buffer>>> {
1308        let load_buffer = worktree.update(cx, |worktree, cx| {
1309            let worktree = worktree.as_local_mut().unwrap();
1310            worktree.load_buffer(path, cx)
1311        });
1312        cx.spawn(|this, mut cx| async move {
1313            let buffer = load_buffer.await?;
1314            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1315            Ok(buffer)
1316        })
1317    }
1318
1319    fn open_remote_buffer_internal(
1320        &mut self,
1321        path: &Arc<Path>,
1322        worktree: &ModelHandle<Worktree>,
1323        cx: &mut ModelContext<Self>,
1324    ) -> Task<Result<ModelHandle<Buffer>>> {
1325        let rpc = self.client.clone();
1326        let project_id = self.remote_id().unwrap();
1327        let remote_worktree_id = worktree.read(cx).id();
1328        let path = path.clone();
1329        let path_string = path.to_string_lossy().to_string();
1330        cx.spawn(|this, mut cx| async move {
1331            let response = rpc
1332                .request(proto::OpenBufferByPath {
1333                    project_id,
1334                    worktree_id: remote_worktree_id.to_proto(),
1335                    path: path_string,
1336                })
1337                .await?;
1338            this.update(&mut cx, |this, cx| {
1339                this.wait_for_buffer(response.buffer_id, cx)
1340            })
1341            .await
1342        })
1343    }
1344
1345    /// LanguageServerName is owned, because it is inserted into a map
1346    fn open_local_buffer_via_lsp(
1347        &mut self,
1348        abs_path: lsp::Url,
1349        language_server_id: usize,
1350        language_server_name: LanguageServerName,
1351        cx: &mut ModelContext<Self>,
1352    ) -> Task<Result<ModelHandle<Buffer>>> {
1353        cx.spawn(|this, mut cx| async move {
1354            let abs_path = abs_path
1355                .to_file_path()
1356                .map_err(|_| anyhow!("can't convert URI to path"))?;
1357            let (worktree, relative_path) = if let Some(result) =
1358                this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1359            {
1360                result
1361            } else {
1362                let worktree = this
1363                    .update(&mut cx, |this, cx| {
1364                        this.create_local_worktree(&abs_path, false, cx)
1365                    })
1366                    .await?;
1367                this.update(&mut cx, |this, cx| {
1368                    this.language_server_ids.insert(
1369                        (worktree.read(cx).id(), language_server_name),
1370                        language_server_id,
1371                    );
1372                });
1373                (worktree, PathBuf::new())
1374            };
1375
1376            let project_path = ProjectPath {
1377                worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1378                path: relative_path.into(),
1379            };
1380            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1381                .await
1382        })
1383    }
1384
1385    pub fn open_buffer_by_id(
1386        &mut self,
1387        id: u64,
1388        cx: &mut ModelContext<Self>,
1389    ) -> Task<Result<ModelHandle<Buffer>>> {
1390        if let Some(buffer) = self.buffer_for_id(id, cx) {
1391            Task::ready(Ok(buffer))
1392        } else if self.is_local() {
1393            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1394        } else if let Some(project_id) = self.remote_id() {
1395            let request = self
1396                .client
1397                .request(proto::OpenBufferById { project_id, id });
1398            cx.spawn(|this, mut cx| async move {
1399                let buffer_id = request.await?.buffer_id;
1400                this.update(&mut cx, |this, cx| this.wait_for_buffer(buffer_id, cx))
1401                    .await
1402            })
1403        } else {
1404            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1405        }
1406    }
1407
1408    pub fn save_buffer_as(
1409        &mut self,
1410        buffer: ModelHandle<Buffer>,
1411        abs_path: PathBuf,
1412        cx: &mut ModelContext<Project>,
1413    ) -> Task<Result<()>> {
1414        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1415        let old_path =
1416            File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1417        cx.spawn(|this, mut cx| async move {
1418            if let Some(old_path) = old_path {
1419                this.update(&mut cx, |this, cx| {
1420                    this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1421                });
1422            }
1423            let (worktree, path) = worktree_task.await?;
1424            worktree
1425                .update(&mut cx, |worktree, cx| {
1426                    worktree
1427                        .as_local_mut()
1428                        .unwrap()
1429                        .save_buffer_as(buffer.clone(), path, cx)
1430                })
1431                .await?;
1432            this.update(&mut cx, |this, cx| {
1433                this.assign_language_to_buffer(&buffer, cx);
1434                this.register_buffer_with_language_server(&buffer, cx);
1435            });
1436            Ok(())
1437        })
1438    }
1439
1440    pub fn get_open_buffer(
1441        &mut self,
1442        path: &ProjectPath,
1443        cx: &mut ModelContext<Self>,
1444    ) -> Option<ModelHandle<Buffer>> {
1445        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1446        self.opened_buffers.values().find_map(|buffer| {
1447            let buffer = buffer.upgrade(cx)?;
1448            let file = File::from_dyn(buffer.read(cx).file())?;
1449            if file.worktree == worktree && file.path() == &path.path {
1450                Some(buffer)
1451            } else {
1452                None
1453            }
1454        })
1455    }
1456
1457    fn register_buffer(
1458        &mut self,
1459        buffer: &ModelHandle<Buffer>,
1460        cx: &mut ModelContext<Self>,
1461    ) -> Result<()> {
1462        let remote_id = buffer.read(cx).remote_id();
1463        let open_buffer = if self.is_remote() || self.is_shared() {
1464            OpenBuffer::Strong(buffer.clone())
1465        } else {
1466            OpenBuffer::Weak(buffer.downgrade())
1467        };
1468
1469        match self.opened_buffers.insert(remote_id, open_buffer) {
1470            None => {}
1471            Some(OpenBuffer::Operations(operations)) => {
1472                buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1473            }
1474            Some(OpenBuffer::Weak(existing_handle)) => {
1475                if existing_handle.upgrade(cx).is_some() {
1476                    Err(anyhow!(
1477                        "already registered buffer with remote id {}",
1478                        remote_id
1479                    ))?
1480                }
1481            }
1482            Some(OpenBuffer::Strong(_)) => Err(anyhow!(
1483                "already registered buffer with remote id {}",
1484                remote_id
1485            ))?,
1486        }
1487        cx.subscribe(buffer, |this, buffer, event, cx| {
1488            this.on_buffer_event(buffer, event, cx);
1489        })
1490        .detach();
1491
1492        self.assign_language_to_buffer(buffer, cx);
1493        self.register_buffer_with_language_server(buffer, cx);
1494        cx.observe_release(buffer, |this, buffer, cx| {
1495            if let Some(file) = File::from_dyn(buffer.file()) {
1496                if file.is_local() {
1497                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1498                    if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1499                        server
1500                            .notify::<lsp::notification::DidCloseTextDocument>(
1501                                lsp::DidCloseTextDocumentParams {
1502                                    text_document: lsp::TextDocumentIdentifier::new(uri),
1503                                },
1504                            )
1505                            .log_err();
1506                    }
1507                }
1508            }
1509        })
1510        .detach();
1511
1512        *self.opened_buffer.0.borrow_mut() = ();
1513        Ok(())
1514    }
1515
1516    fn register_buffer_with_language_server(
1517        &mut self,
1518        buffer_handle: &ModelHandle<Buffer>,
1519        cx: &mut ModelContext<Self>,
1520    ) {
1521        let buffer = buffer_handle.read(cx);
1522        let buffer_id = buffer.remote_id();
1523        if let Some(file) = File::from_dyn(buffer.file()) {
1524            if file.is_local() {
1525                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1526                let initial_snapshot = buffer.text_snapshot();
1527
1528                let mut language_server = None;
1529                let mut language_id = None;
1530                if let Some(language) = buffer.language() {
1531                    let worktree_id = file.worktree_id(cx);
1532                    if let Some(adapter) = language.lsp_adapter() {
1533                        language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
1534                        language_server = self
1535                            .language_server_ids
1536                            .get(&(worktree_id, adapter.name.clone()))
1537                            .and_then(|id| self.language_servers.get(id))
1538                            .and_then(|server_state| {
1539                                if let LanguageServerState::Running { server, .. } = server_state {
1540                                    Some(server.clone())
1541                                } else {
1542                                    None
1543                                }
1544                            });
1545                    }
1546                }
1547
1548                if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1549                    if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1550                        self.update_buffer_diagnostics(buffer_handle, diagnostics, None, cx)
1551                            .log_err();
1552                    }
1553                }
1554
1555                if let Some(server) = language_server {
1556                    server
1557                        .notify::<lsp::notification::DidOpenTextDocument>(
1558                            lsp::DidOpenTextDocumentParams {
1559                                text_document: lsp::TextDocumentItem::new(
1560                                    uri,
1561                                    language_id.unwrap_or_default(),
1562                                    0,
1563                                    initial_snapshot.text(),
1564                                ),
1565                            },
1566                        )
1567                        .log_err();
1568                    buffer_handle.update(cx, |buffer, cx| {
1569                        buffer.set_completion_triggers(
1570                            server
1571                                .capabilities()
1572                                .completion_provider
1573                                .as_ref()
1574                                .and_then(|provider| provider.trigger_characters.clone())
1575                                .unwrap_or_default(),
1576                            cx,
1577                        )
1578                    });
1579                    self.buffer_snapshots
1580                        .insert(buffer_id, vec![(0, initial_snapshot)]);
1581                }
1582            }
1583        }
1584    }
1585
1586    fn unregister_buffer_from_language_server(
1587        &mut self,
1588        buffer: &ModelHandle<Buffer>,
1589        old_path: PathBuf,
1590        cx: &mut ModelContext<Self>,
1591    ) {
1592        buffer.update(cx, |buffer, cx| {
1593            buffer.update_diagnostics(Default::default(), cx);
1594            self.buffer_snapshots.remove(&buffer.remote_id());
1595            if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1596                language_server
1597                    .notify::<lsp::notification::DidCloseTextDocument>(
1598                        lsp::DidCloseTextDocumentParams {
1599                            text_document: lsp::TextDocumentIdentifier::new(
1600                                lsp::Url::from_file_path(old_path).unwrap(),
1601                            ),
1602                        },
1603                    )
1604                    .log_err();
1605            }
1606        });
1607    }
1608
1609    fn on_buffer_event(
1610        &mut self,
1611        buffer: ModelHandle<Buffer>,
1612        event: &BufferEvent,
1613        cx: &mut ModelContext<Self>,
1614    ) -> Option<()> {
1615        match event {
1616            BufferEvent::Operation(operation) => {
1617                if let Some(project_id) = self.remote_id() {
1618                    let request = self.client.request(proto::UpdateBuffer {
1619                        project_id,
1620                        buffer_id: buffer.read(cx).remote_id(),
1621                        operations: vec![language::proto::serialize_operation(operation)],
1622                    });
1623                    cx.background().spawn(request).detach_and_log_err(cx);
1624                }
1625            }
1626            BufferEvent::Edited { .. } => {
1627                let language_server = self
1628                    .language_server_for_buffer(buffer.read(cx), cx)
1629                    .map(|(_, server)| server.clone())?;
1630                let buffer = buffer.read(cx);
1631                let file = File::from_dyn(buffer.file())?;
1632                let abs_path = file.as_local()?.abs_path(cx);
1633                let uri = lsp::Url::from_file_path(abs_path).unwrap();
1634                let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1635                let (version, prev_snapshot) = buffer_snapshots.last()?;
1636                let next_snapshot = buffer.text_snapshot();
1637                let next_version = version + 1;
1638
1639                let content_changes = buffer
1640                    .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1641                    .map(|edit| {
1642                        let edit_start = edit.new.start.0;
1643                        let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1644                        let new_text = next_snapshot
1645                            .text_for_range(edit.new.start.1..edit.new.end.1)
1646                            .collect();
1647                        lsp::TextDocumentContentChangeEvent {
1648                            range: Some(lsp::Range::new(
1649                                point_to_lsp(edit_start),
1650                                point_to_lsp(edit_end),
1651                            )),
1652                            range_length: None,
1653                            text: new_text,
1654                        }
1655                    })
1656                    .collect();
1657
1658                buffer_snapshots.push((next_version, next_snapshot));
1659
1660                language_server
1661                    .notify::<lsp::notification::DidChangeTextDocument>(
1662                        lsp::DidChangeTextDocumentParams {
1663                            text_document: lsp::VersionedTextDocumentIdentifier::new(
1664                                uri,
1665                                next_version,
1666                            ),
1667                            content_changes,
1668                        },
1669                    )
1670                    .log_err();
1671            }
1672            BufferEvent::Saved => {
1673                let file = File::from_dyn(buffer.read(cx).file())?;
1674                let worktree_id = file.worktree_id(cx);
1675                let abs_path = file.as_local()?.abs_path(cx);
1676                let text_document = lsp::TextDocumentIdentifier {
1677                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
1678                };
1679
1680                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
1681                    server
1682                        .notify::<lsp::notification::DidSaveTextDocument>(
1683                            lsp::DidSaveTextDocumentParams {
1684                                text_document: text_document.clone(),
1685                                text: None,
1686                            },
1687                        )
1688                        .log_err();
1689                }
1690
1691                // After saving a buffer, simulate disk-based diagnostics being finished for languages
1692                // that don't support a disk-based progress token.
1693                let (lsp_adapter, language_server) =
1694                    self.language_server_for_buffer(buffer.read(cx), cx)?;
1695                if lsp_adapter.disk_based_diagnostics_progress_token.is_none() {
1696                    let server_id = language_server.server_id();
1697                    self.disk_based_diagnostics_finished(server_id, cx);
1698                    self.broadcast_language_server_update(
1699                        server_id,
1700                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1701                            proto::LspDiskBasedDiagnosticsUpdated {},
1702                        ),
1703                    );
1704                }
1705            }
1706            _ => {}
1707        }
1708
1709        None
1710    }
1711
1712    fn language_servers_for_worktree(
1713        &self,
1714        worktree_id: WorktreeId,
1715    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
1716        self.language_server_ids
1717            .iter()
1718            .filter_map(move |((language_server_worktree_id, _), id)| {
1719                if *language_server_worktree_id == worktree_id {
1720                    if let Some(LanguageServerState::Running {
1721                        adapter,
1722                        language,
1723                        server,
1724                    }) = self.language_servers.get(id)
1725                    {
1726                        return Some((adapter, language, server));
1727                    }
1728                }
1729                None
1730            })
1731    }
1732
1733    fn maintain_buffer_languages(
1734        languages: &LanguageRegistry,
1735        cx: &mut ModelContext<Project>,
1736    ) -> Task<()> {
1737        let mut subscription = languages.subscribe();
1738        cx.spawn_weak(|project, mut cx| async move {
1739            while let Some(()) = subscription.next().await {
1740                if let Some(project) = project.upgrade(&cx) {
1741                    project.update(&mut cx, |project, cx| {
1742                        let mut buffers_without_language = Vec::new();
1743                        for buffer in project.opened_buffers.values() {
1744                            if let Some(buffer) = buffer.upgrade(cx) {
1745                                if buffer.read(cx).language().is_none() {
1746                                    buffers_without_language.push(buffer);
1747                                }
1748                            }
1749                        }
1750
1751                        for buffer in buffers_without_language {
1752                            project.assign_language_to_buffer(&buffer, cx);
1753                            project.register_buffer_with_language_server(&buffer, cx);
1754                        }
1755                    });
1756                }
1757            }
1758        })
1759    }
1760
1761    fn assign_language_to_buffer(
1762        &mut self,
1763        buffer: &ModelHandle<Buffer>,
1764        cx: &mut ModelContext<Self>,
1765    ) -> Option<()> {
1766        // If the buffer has a language, set it and start the language server if we haven't already.
1767        let full_path = buffer.read(cx).file()?.full_path(cx);
1768        let new_language = self.languages.select_language(&full_path)?;
1769        buffer.update(cx, |buffer, cx| {
1770            if buffer.language().map_or(true, |old_language| {
1771                !Arc::ptr_eq(old_language, &new_language)
1772            }) {
1773                buffer.set_language_registry(self.languages.clone());
1774                buffer.set_language(Some(new_language.clone()), cx);
1775            }
1776        });
1777
1778        let file = File::from_dyn(buffer.read(cx).file())?;
1779        let worktree = file.worktree.read(cx).as_local()?;
1780        let worktree_id = worktree.id();
1781        let worktree_abs_path = worktree.abs_path().clone();
1782        self.start_language_server(worktree_id, worktree_abs_path, new_language, cx);
1783
1784        None
1785    }
1786
1787    fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
1788        use serde_json::Value;
1789
1790        match (source, target) {
1791            (Value::Object(source), Value::Object(target)) => {
1792                for (key, value) in source {
1793                    if let Some(target) = target.get_mut(&key) {
1794                        Self::merge_json_value_into(value, target);
1795                    } else {
1796                        target.insert(key.clone(), value);
1797                    }
1798                }
1799            }
1800
1801            (source, target) => *target = source,
1802        }
1803    }
1804
1805    fn start_language_server(
1806        &mut self,
1807        worktree_id: WorktreeId,
1808        worktree_path: Arc<Path>,
1809        language: Arc<Language>,
1810        cx: &mut ModelContext<Self>,
1811    ) {
1812        if !cx
1813            .global::<Settings>()
1814            .enable_language_server(Some(&language.name()))
1815        {
1816            return;
1817        }
1818
1819        let adapter = if let Some(adapter) = language.lsp_adapter() {
1820            adapter
1821        } else {
1822            return;
1823        };
1824        let key = (worktree_id, adapter.name.clone());
1825
1826        let mut initialization_options = adapter.initialization_options.clone();
1827
1828        let lsp = &cx.global::<Settings>().lsp.get(&adapter.name.0);
1829        let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
1830        match (&mut initialization_options, override_options) {
1831            (Some(initialization_options), Some(override_options)) => {
1832                Self::merge_json_value_into(override_options, initialization_options);
1833            }
1834
1835            (None, override_options) => initialization_options = override_options,
1836
1837            _ => {}
1838        }
1839
1840        self.language_server_ids
1841            .entry(key.clone())
1842            .or_insert_with(|| {
1843                let server_id = post_inc(&mut self.next_language_server_id);
1844                let language_server = self.languages.start_language_server(
1845                    server_id,
1846                    language.clone(),
1847                    worktree_path,
1848                    self.client.http_client(),
1849                    cx,
1850                );
1851                self.language_servers.insert(
1852                    server_id,
1853                    LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
1854                        let language_server = language_server?.await.log_err()?;
1855                        let language_server = language_server
1856                            .initialize(initialization_options)
1857                            .await
1858                            .log_err()?;
1859                        let this = this.upgrade(&cx)?;
1860
1861                        language_server
1862                            .on_notification::<lsp::notification::PublishDiagnostics, _>({
1863                                let this = this.downgrade();
1864                                let adapter = adapter.clone();
1865                                move |mut params, cx| {
1866                                    let this = this;
1867                                    let adapter = adapter.clone();
1868                                    cx.spawn(|mut cx| async move {
1869                                        adapter.process_diagnostics(&mut params).await;
1870                                        if let Some(this) = this.upgrade(&cx) {
1871                                            this.update(&mut cx, |this, cx| {
1872                                                this.update_diagnostics(
1873                                                    server_id,
1874                                                    params,
1875                                                    &adapter.disk_based_diagnostic_sources,
1876                                                    cx,
1877                                                )
1878                                                .log_err();
1879                                            });
1880                                        }
1881                                    })
1882                                    .detach();
1883                                }
1884                            })
1885                            .detach();
1886
1887                        language_server
1888                            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
1889                                let settings = this.read_with(&cx, |this, _| {
1890                                    this.language_server_settings.clone()
1891                                });
1892                                move |params, _| {
1893                                    let settings = settings.lock().clone();
1894                                    async move {
1895                                        Ok(params
1896                                            .items
1897                                            .into_iter()
1898                                            .map(|item| {
1899                                                if let Some(section) = &item.section {
1900                                                    settings
1901                                                        .get(section)
1902                                                        .cloned()
1903                                                        .unwrap_or(serde_json::Value::Null)
1904                                                } else {
1905                                                    settings.clone()
1906                                                }
1907                                            })
1908                                            .collect())
1909                                    }
1910                                }
1911                            })
1912                            .detach();
1913
1914                        // Even though we don't have handling for these requests, respond to them to
1915                        // avoid stalling any language server like `gopls` which waits for a response
1916                        // to these requests when initializing.
1917                        language_server
1918                            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
1919                                let this = this.downgrade();
1920                                move |params, mut cx| async move {
1921                                    if let Some(this) = this.upgrade(&cx) {
1922                                        this.update(&mut cx, |this, _| {
1923                                            if let Some(status) =
1924                                                this.language_server_statuses.get_mut(&server_id)
1925                                            {
1926                                                if let lsp::NumberOrString::String(token) =
1927                                                    params.token
1928                                                {
1929                                                    status.progress_tokens.insert(token);
1930                                                }
1931                                            }
1932                                        });
1933                                    }
1934                                    Ok(())
1935                                }
1936                            })
1937                            .detach();
1938                        language_server
1939                            .on_request::<lsp::request::RegisterCapability, _, _>(|_, _| async {
1940                                Ok(())
1941                            })
1942                            .detach();
1943
1944                        language_server
1945                            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
1946                                let this = this.downgrade();
1947                                let adapter = adapter.clone();
1948                                let language_server = language_server.clone();
1949                                move |params, cx| {
1950                                    Self::on_lsp_workspace_edit(
1951                                        this,
1952                                        params,
1953                                        server_id,
1954                                        adapter.clone(),
1955                                        language_server.clone(),
1956                                        cx,
1957                                    )
1958                                }
1959                            })
1960                            .detach();
1961
1962                        let disk_based_diagnostics_progress_token =
1963                            adapter.disk_based_diagnostics_progress_token.clone();
1964
1965                        language_server
1966                            .on_notification::<lsp::notification::Progress, _>({
1967                                let this = this.downgrade();
1968                                move |params, mut cx| {
1969                                    if let Some(this) = this.upgrade(&cx) {
1970                                        this.update(&mut cx, |this, cx| {
1971                                            this.on_lsp_progress(
1972                                                params,
1973                                                server_id,
1974                                                disk_based_diagnostics_progress_token.clone(),
1975                                                cx,
1976                                            );
1977                                        });
1978                                    }
1979                                }
1980                            })
1981                            .detach();
1982
1983                        this.update(&mut cx, |this, cx| {
1984                            // If the language server for this key doesn't match the server id, don't store the
1985                            // server. Which will cause it to be dropped, killing the process
1986                            if this
1987                                .language_server_ids
1988                                .get(&key)
1989                                .map(|id| id != &server_id)
1990                                .unwrap_or(false)
1991                            {
1992                                return None;
1993                            }
1994
1995                            // Update language_servers collection with Running variant of LanguageServerState
1996                            // indicating that the server is up and running and ready
1997                            this.language_servers.insert(
1998                                server_id,
1999                                LanguageServerState::Running {
2000                                    adapter: adapter.clone(),
2001                                    language,
2002                                    server: language_server.clone(),
2003                                },
2004                            );
2005                            this.language_server_statuses.insert(
2006                                server_id,
2007                                LanguageServerStatus {
2008                                    name: language_server.name().to_string(),
2009                                    pending_work: Default::default(),
2010                                    has_pending_diagnostic_updates: false,
2011                                    progress_tokens: Default::default(),
2012                                },
2013                            );
2014                            language_server
2015                                .notify::<lsp::notification::DidChangeConfiguration>(
2016                                    lsp::DidChangeConfigurationParams {
2017                                        settings: this.language_server_settings.lock().clone(),
2018                                    },
2019                                )
2020                                .ok();
2021
2022                            if let Some(project_id) = this.remote_id() {
2023                                this.client
2024                                    .send(proto::StartLanguageServer {
2025                                        project_id,
2026                                        server: Some(proto::LanguageServer {
2027                                            id: server_id as u64,
2028                                            name: language_server.name().to_string(),
2029                                        }),
2030                                    })
2031                                    .log_err();
2032                            }
2033
2034                            // Tell the language server about every open buffer in the worktree that matches the language.
2035                            for buffer in this.opened_buffers.values() {
2036                                if let Some(buffer_handle) = buffer.upgrade(cx) {
2037                                    let buffer = buffer_handle.read(cx);
2038                                    let file = if let Some(file) = File::from_dyn(buffer.file()) {
2039                                        file
2040                                    } else {
2041                                        continue;
2042                                    };
2043                                    let language = if let Some(language) = buffer.language() {
2044                                        language
2045                                    } else {
2046                                        continue;
2047                                    };
2048                                    if file.worktree.read(cx).id() != key.0
2049                                        || language.lsp_adapter().map(|a| a.name.clone())
2050                                            != Some(key.1.clone())
2051                                    {
2052                                        continue;
2053                                    }
2054
2055                                    let file = file.as_local()?;
2056                                    let versions = this
2057                                        .buffer_snapshots
2058                                        .entry(buffer.remote_id())
2059                                        .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2060                                    let (version, initial_snapshot) = versions.last().unwrap();
2061                                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2062                                    language_server
2063                                        .notify::<lsp::notification::DidOpenTextDocument>(
2064                                            lsp::DidOpenTextDocumentParams {
2065                                                text_document: lsp::TextDocumentItem::new(
2066                                                    uri,
2067                                                    adapter
2068                                                        .language_ids
2069                                                        .get(language.name().as_ref())
2070                                                        .cloned()
2071                                                        .unwrap_or_default(),
2072                                                    *version,
2073                                                    initial_snapshot.text(),
2074                                                ),
2075                                            },
2076                                        )
2077                                        .log_err()?;
2078                                    buffer_handle.update(cx, |buffer, cx| {
2079                                        buffer.set_completion_triggers(
2080                                            language_server
2081                                                .capabilities()
2082                                                .completion_provider
2083                                                .as_ref()
2084                                                .and_then(|provider| {
2085                                                    provider.trigger_characters.clone()
2086                                                })
2087                                                .unwrap_or_default(),
2088                                            cx,
2089                                        )
2090                                    });
2091                                }
2092                            }
2093
2094                            cx.notify();
2095                            Some(language_server)
2096                        })
2097                    })),
2098                );
2099
2100                server_id
2101            });
2102    }
2103
2104    // Returns a list of all of the worktrees which no longer have a language server and the root path
2105    // for the stopped server
2106    fn stop_language_server(
2107        &mut self,
2108        worktree_id: WorktreeId,
2109        adapter_name: LanguageServerName,
2110        cx: &mut ModelContext<Self>,
2111    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2112        let key = (worktree_id, adapter_name);
2113        if let Some(server_id) = self.language_server_ids.remove(&key) {
2114            // Remove other entries for this language server as well
2115            let mut orphaned_worktrees = vec![worktree_id];
2116            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2117            for other_key in other_keys {
2118                if self.language_server_ids.get(&other_key) == Some(&server_id) {
2119                    self.language_server_ids.remove(&other_key);
2120                    orphaned_worktrees.push(other_key.0);
2121                }
2122            }
2123
2124            self.language_server_statuses.remove(&server_id);
2125            cx.notify();
2126
2127            let server_state = self.language_servers.remove(&server_id);
2128            cx.spawn_weak(|this, mut cx| async move {
2129                let mut root_path = None;
2130
2131                let server = match server_state {
2132                    Some(LanguageServerState::Starting(started_language_server)) => {
2133                        started_language_server.await
2134                    }
2135                    Some(LanguageServerState::Running { server, .. }) => Some(server),
2136                    None => None,
2137                };
2138
2139                if let Some(server) = server {
2140                    root_path = Some(server.root_path().clone());
2141                    if let Some(shutdown) = server.shutdown() {
2142                        shutdown.await;
2143                    }
2144                }
2145
2146                if let Some(this) = this.upgrade(&cx) {
2147                    this.update(&mut cx, |this, cx| {
2148                        this.language_server_statuses.remove(&server_id);
2149                        cx.notify();
2150                    });
2151                }
2152
2153                (root_path, orphaned_worktrees)
2154            })
2155        } else {
2156            Task::ready((None, Vec::new()))
2157        }
2158    }
2159
2160    pub fn restart_language_servers_for_buffers(
2161        &mut self,
2162        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2163        cx: &mut ModelContext<Self>,
2164    ) -> Option<()> {
2165        let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
2166            .into_iter()
2167            .filter_map(|buffer| {
2168                let file = File::from_dyn(buffer.read(cx).file())?;
2169                let worktree = file.worktree.read(cx).as_local()?;
2170                let worktree_id = worktree.id();
2171                let worktree_abs_path = worktree.abs_path().clone();
2172                let full_path = file.full_path(cx);
2173                Some((worktree_id, worktree_abs_path, full_path))
2174            })
2175            .collect();
2176        for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
2177            let language = self.languages.select_language(&full_path)?;
2178            self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2179        }
2180
2181        None
2182    }
2183
2184    fn restart_language_server(
2185        &mut self,
2186        worktree_id: WorktreeId,
2187        fallback_path: Arc<Path>,
2188        language: Arc<Language>,
2189        cx: &mut ModelContext<Self>,
2190    ) {
2191        let adapter = if let Some(adapter) = language.lsp_adapter() {
2192            adapter
2193        } else {
2194            return;
2195        };
2196
2197        let server_name = adapter.name.clone();
2198        let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2199        cx.spawn_weak(|this, mut cx| async move {
2200            let (original_root_path, orphaned_worktrees) = stop.await;
2201            if let Some(this) = this.upgrade(&cx) {
2202                this.update(&mut cx, |this, cx| {
2203                    // Attempt to restart using original server path. Fallback to passed in
2204                    // path if we could not retrieve the root path
2205                    let root_path = original_root_path
2206                        .map(|path_buf| Arc::from(path_buf.as_path()))
2207                        .unwrap_or(fallback_path);
2208
2209                    this.start_language_server(worktree_id, root_path, language, cx);
2210
2211                    // Lookup new server id and set it for each of the orphaned worktrees
2212                    if let Some(new_server_id) = this
2213                        .language_server_ids
2214                        .get(&(worktree_id, server_name.clone()))
2215                        .cloned()
2216                    {
2217                        for orphaned_worktree in orphaned_worktrees {
2218                            this.language_server_ids
2219                                .insert((orphaned_worktree, server_name.clone()), new_server_id);
2220                        }
2221                    }
2222                });
2223            }
2224        })
2225        .detach();
2226    }
2227
2228    fn on_lsp_progress(
2229        &mut self,
2230        progress: lsp::ProgressParams,
2231        server_id: usize,
2232        disk_based_diagnostics_progress_token: Option<String>,
2233        cx: &mut ModelContext<Self>,
2234    ) {
2235        let token = match progress.token {
2236            lsp::NumberOrString::String(token) => token,
2237            lsp::NumberOrString::Number(token) => {
2238                log::info!("skipping numeric progress token {}", token);
2239                return;
2240            }
2241        };
2242        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2243        let language_server_status =
2244            if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2245                status
2246            } else {
2247                return;
2248            };
2249
2250        if !language_server_status.progress_tokens.contains(&token) {
2251            return;
2252        }
2253
2254        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
2255            .as_ref()
2256            .map_or(false, |disk_based_token| {
2257                token.starts_with(disk_based_token)
2258            });
2259
2260        match progress {
2261            lsp::WorkDoneProgress::Begin(report) => {
2262                if is_disk_based_diagnostics_progress {
2263                    language_server_status.has_pending_diagnostic_updates = true;
2264                    self.disk_based_diagnostics_started(server_id, cx);
2265                    self.broadcast_language_server_update(
2266                        server_id,
2267                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2268                            proto::LspDiskBasedDiagnosticsUpdating {},
2269                        ),
2270                    );
2271                } else {
2272                    self.on_lsp_work_start(
2273                        server_id,
2274                        token.clone(),
2275                        LanguageServerProgress {
2276                            message: report.message.clone(),
2277                            percentage: report.percentage.map(|p| p as usize),
2278                            last_update_at: Instant::now(),
2279                        },
2280                        cx,
2281                    );
2282                    self.broadcast_language_server_update(
2283                        server_id,
2284                        proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2285                            token,
2286                            message: report.message,
2287                            percentage: report.percentage.map(|p| p as u32),
2288                        }),
2289                    );
2290                }
2291            }
2292            lsp::WorkDoneProgress::Report(report) => {
2293                if !is_disk_based_diagnostics_progress {
2294                    self.on_lsp_work_progress(
2295                        server_id,
2296                        token.clone(),
2297                        LanguageServerProgress {
2298                            message: report.message.clone(),
2299                            percentage: report.percentage.map(|p| p as usize),
2300                            last_update_at: Instant::now(),
2301                        },
2302                        cx,
2303                    );
2304                    self.broadcast_language_server_update(
2305                        server_id,
2306                        proto::update_language_server::Variant::WorkProgress(
2307                            proto::LspWorkProgress {
2308                                token,
2309                                message: report.message,
2310                                percentage: report.percentage.map(|p| p as u32),
2311                            },
2312                        ),
2313                    );
2314                }
2315            }
2316            lsp::WorkDoneProgress::End(_) => {
2317                language_server_status.progress_tokens.remove(&token);
2318
2319                if is_disk_based_diagnostics_progress {
2320                    language_server_status.has_pending_diagnostic_updates = false;
2321                    self.disk_based_diagnostics_finished(server_id, cx);
2322                    self.broadcast_language_server_update(
2323                        server_id,
2324                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2325                            proto::LspDiskBasedDiagnosticsUpdated {},
2326                        ),
2327                    );
2328                } else {
2329                    self.on_lsp_work_end(server_id, token.clone(), cx);
2330                    self.broadcast_language_server_update(
2331                        server_id,
2332                        proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2333                            token,
2334                        }),
2335                    );
2336                }
2337            }
2338        }
2339    }
2340
2341    fn on_lsp_work_start(
2342        &mut self,
2343        language_server_id: usize,
2344        token: String,
2345        progress: LanguageServerProgress,
2346        cx: &mut ModelContext<Self>,
2347    ) {
2348        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2349            status.pending_work.insert(token, progress);
2350            cx.notify();
2351        }
2352    }
2353
2354    fn on_lsp_work_progress(
2355        &mut self,
2356        language_server_id: usize,
2357        token: String,
2358        progress: LanguageServerProgress,
2359        cx: &mut ModelContext<Self>,
2360    ) {
2361        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2362            let entry = status
2363                .pending_work
2364                .entry(token)
2365                .or_insert(LanguageServerProgress {
2366                    message: Default::default(),
2367                    percentage: Default::default(),
2368                    last_update_at: progress.last_update_at,
2369                });
2370            if progress.message.is_some() {
2371                entry.message = progress.message;
2372            }
2373            if progress.percentage.is_some() {
2374                entry.percentage = progress.percentage;
2375            }
2376            entry.last_update_at = progress.last_update_at;
2377            cx.notify();
2378        }
2379    }
2380
2381    fn on_lsp_work_end(
2382        &mut self,
2383        language_server_id: usize,
2384        token: String,
2385        cx: &mut ModelContext<Self>,
2386    ) {
2387        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2388            status.pending_work.remove(&token);
2389            cx.notify();
2390        }
2391    }
2392
2393    async fn on_lsp_workspace_edit(
2394        this: WeakModelHandle<Self>,
2395        params: lsp::ApplyWorkspaceEditParams,
2396        server_id: usize,
2397        adapter: Arc<CachedLspAdapter>,
2398        language_server: Arc<LanguageServer>,
2399        mut cx: AsyncAppContext,
2400    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2401        let this = this
2402            .upgrade(&cx)
2403            .ok_or_else(|| anyhow!("project project closed"))?;
2404        let transaction = Self::deserialize_workspace_edit(
2405            this.clone(),
2406            params.edit,
2407            true,
2408            adapter.clone(),
2409            language_server.clone(),
2410            &mut cx,
2411        )
2412        .await
2413        .log_err();
2414        this.update(&mut cx, |this, _| {
2415            if let Some(transaction) = transaction {
2416                this.last_workspace_edits_by_language_server
2417                    .insert(server_id, transaction);
2418            }
2419        });
2420        Ok(lsp::ApplyWorkspaceEditResponse {
2421            applied: true,
2422            failed_change: None,
2423            failure_reason: None,
2424        })
2425    }
2426
2427    fn broadcast_language_server_update(
2428        &self,
2429        language_server_id: usize,
2430        event: proto::update_language_server::Variant,
2431    ) {
2432        if let Some(project_id) = self.remote_id() {
2433            self.client
2434                .send(proto::UpdateLanguageServer {
2435                    project_id,
2436                    language_server_id: language_server_id as u64,
2437                    variant: Some(event),
2438                })
2439                .log_err();
2440        }
2441    }
2442
2443    pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2444        for server_state in self.language_servers.values() {
2445            if let LanguageServerState::Running { server, .. } = server_state {
2446                server
2447                    .notify::<lsp::notification::DidChangeConfiguration>(
2448                        lsp::DidChangeConfigurationParams {
2449                            settings: settings.clone(),
2450                        },
2451                    )
2452                    .ok();
2453            }
2454        }
2455        *self.language_server_settings.lock() = settings;
2456    }
2457
2458    pub fn language_server_statuses(
2459        &self,
2460    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2461        self.language_server_statuses.values()
2462    }
2463
2464    pub fn update_diagnostics(
2465        &mut self,
2466        language_server_id: usize,
2467        params: lsp::PublishDiagnosticsParams,
2468        disk_based_sources: &[String],
2469        cx: &mut ModelContext<Self>,
2470    ) -> Result<()> {
2471        let abs_path = params
2472            .uri
2473            .to_file_path()
2474            .map_err(|_| anyhow!("URI is not a file"))?;
2475        let mut diagnostics = Vec::default();
2476        let mut primary_diagnostic_group_ids = HashMap::default();
2477        let mut sources_by_group_id = HashMap::default();
2478        let mut supporting_diagnostics = HashMap::default();
2479        for diagnostic in &params.diagnostics {
2480            let source = diagnostic.source.as_ref();
2481            let code = diagnostic.code.as_ref().map(|code| match code {
2482                lsp::NumberOrString::Number(code) => code.to_string(),
2483                lsp::NumberOrString::String(code) => code.clone(),
2484            });
2485            let range = range_from_lsp(diagnostic.range);
2486            let is_supporting = diagnostic
2487                .related_information
2488                .as_ref()
2489                .map_or(false, |infos| {
2490                    infos.iter().any(|info| {
2491                        primary_diagnostic_group_ids.contains_key(&(
2492                            source,
2493                            code.clone(),
2494                            range_from_lsp(info.location.range),
2495                        ))
2496                    })
2497                });
2498
2499            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2500                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2501            });
2502
2503            if is_supporting {
2504                supporting_diagnostics.insert(
2505                    (source, code.clone(), range),
2506                    (diagnostic.severity, is_unnecessary),
2507                );
2508            } else {
2509                let group_id = post_inc(&mut self.next_diagnostic_group_id);
2510                let is_disk_based =
2511                    source.map_or(false, |source| disk_based_sources.contains(source));
2512
2513                sources_by_group_id.insert(group_id, source);
2514                primary_diagnostic_group_ids
2515                    .insert((source, code.clone(), range.clone()), group_id);
2516
2517                diagnostics.push(DiagnosticEntry {
2518                    range,
2519                    diagnostic: Diagnostic {
2520                        code: code.clone(),
2521                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2522                        message: diagnostic.message.clone(),
2523                        group_id,
2524                        is_primary: true,
2525                        is_valid: true,
2526                        is_disk_based,
2527                        is_unnecessary,
2528                    },
2529                });
2530                if let Some(infos) = &diagnostic.related_information {
2531                    for info in infos {
2532                        if info.location.uri == params.uri && !info.message.is_empty() {
2533                            let range = range_from_lsp(info.location.range);
2534                            diagnostics.push(DiagnosticEntry {
2535                                range,
2536                                diagnostic: Diagnostic {
2537                                    code: code.clone(),
2538                                    severity: DiagnosticSeverity::INFORMATION,
2539                                    message: info.message.clone(),
2540                                    group_id,
2541                                    is_primary: false,
2542                                    is_valid: true,
2543                                    is_disk_based,
2544                                    is_unnecessary: false,
2545                                },
2546                            });
2547                        }
2548                    }
2549                }
2550            }
2551        }
2552
2553        for entry in &mut diagnostics {
2554            let diagnostic = &mut entry.diagnostic;
2555            if !diagnostic.is_primary {
2556                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2557                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2558                    source,
2559                    diagnostic.code.clone(),
2560                    entry.range.clone(),
2561                )) {
2562                    if let Some(severity) = severity {
2563                        diagnostic.severity = severity;
2564                    }
2565                    diagnostic.is_unnecessary = is_unnecessary;
2566                }
2567            }
2568        }
2569
2570        self.update_diagnostic_entries(
2571            language_server_id,
2572            abs_path,
2573            params.version,
2574            diagnostics,
2575            cx,
2576        )?;
2577        Ok(())
2578    }
2579
2580    pub fn update_diagnostic_entries(
2581        &mut self,
2582        language_server_id: usize,
2583        abs_path: PathBuf,
2584        version: Option<i32>,
2585        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2586        cx: &mut ModelContext<Project>,
2587    ) -> Result<(), anyhow::Error> {
2588        let (worktree, relative_path) = self
2589            .find_local_worktree(&abs_path, cx)
2590            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2591
2592        let project_path = ProjectPath {
2593            worktree_id: worktree.read(cx).id(),
2594            path: relative_path.into(),
2595        };
2596        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2597            self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2598        }
2599
2600        let updated = worktree.update(cx, |worktree, cx| {
2601            worktree
2602                .as_local_mut()
2603                .ok_or_else(|| anyhow!("not a local worktree"))?
2604                .update_diagnostics(
2605                    language_server_id,
2606                    project_path.path.clone(),
2607                    diagnostics,
2608                    cx,
2609                )
2610        })?;
2611        if updated {
2612            cx.emit(Event::DiagnosticsUpdated {
2613                language_server_id,
2614                path: project_path,
2615            });
2616        }
2617        Ok(())
2618    }
2619
2620    fn update_buffer_diagnostics(
2621        &mut self,
2622        buffer: &ModelHandle<Buffer>,
2623        mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2624        version: Option<i32>,
2625        cx: &mut ModelContext<Self>,
2626    ) -> Result<()> {
2627        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2628            Ordering::Equal
2629                .then_with(|| b.is_primary.cmp(&a.is_primary))
2630                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2631                .then_with(|| a.severity.cmp(&b.severity))
2632                .then_with(|| a.message.cmp(&b.message))
2633        }
2634
2635        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2636
2637        diagnostics.sort_unstable_by(|a, b| {
2638            Ordering::Equal
2639                .then_with(|| a.range.start.cmp(&b.range.start))
2640                .then_with(|| b.range.end.cmp(&a.range.end))
2641                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2642        });
2643
2644        let mut sanitized_diagnostics = Vec::new();
2645        let edits_since_save = Patch::new(
2646            snapshot
2647                .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
2648                .collect(),
2649        );
2650        for entry in diagnostics {
2651            let start;
2652            let end;
2653            if entry.diagnostic.is_disk_based {
2654                // Some diagnostics are based on files on disk instead of buffers'
2655                // current contents. Adjust these diagnostics' ranges to reflect
2656                // any unsaved edits.
2657                start = edits_since_save.old_to_new(entry.range.start);
2658                end = edits_since_save.old_to_new(entry.range.end);
2659            } else {
2660                start = entry.range.start;
2661                end = entry.range.end;
2662            }
2663
2664            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2665                ..snapshot.clip_point_utf16(end, Bias::Right);
2666
2667            // Expand empty ranges by one character
2668            if range.start == range.end {
2669                range.end.column += 1;
2670                range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2671                if range.start == range.end && range.end.column > 0 {
2672                    range.start.column -= 1;
2673                    range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2674                }
2675            }
2676
2677            sanitized_diagnostics.push(DiagnosticEntry {
2678                range,
2679                diagnostic: entry.diagnostic,
2680            });
2681        }
2682        drop(edits_since_save);
2683
2684        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2685        buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2686        Ok(())
2687    }
2688
2689    pub fn reload_buffers(
2690        &self,
2691        buffers: HashSet<ModelHandle<Buffer>>,
2692        push_to_history: bool,
2693        cx: &mut ModelContext<Self>,
2694    ) -> Task<Result<ProjectTransaction>> {
2695        let mut local_buffers = Vec::new();
2696        let mut remote_buffers = None;
2697        for buffer_handle in buffers {
2698            let buffer = buffer_handle.read(cx);
2699            if buffer.is_dirty() {
2700                if let Some(file) = File::from_dyn(buffer.file()) {
2701                    if file.is_local() {
2702                        local_buffers.push(buffer_handle);
2703                    } else {
2704                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2705                    }
2706                }
2707            }
2708        }
2709
2710        let remote_buffers = self.remote_id().zip(remote_buffers);
2711        let client = self.client.clone();
2712
2713        cx.spawn(|this, mut cx| async move {
2714            let mut project_transaction = ProjectTransaction::default();
2715
2716            if let Some((project_id, remote_buffers)) = remote_buffers {
2717                let response = client
2718                    .request(proto::ReloadBuffers {
2719                        project_id,
2720                        buffer_ids: remote_buffers
2721                            .iter()
2722                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2723                            .collect(),
2724                    })
2725                    .await?
2726                    .transaction
2727                    .ok_or_else(|| anyhow!("missing transaction"))?;
2728                project_transaction = this
2729                    .update(&mut cx, |this, cx| {
2730                        this.deserialize_project_transaction(response, push_to_history, cx)
2731                    })
2732                    .await?;
2733            }
2734
2735            for buffer in local_buffers {
2736                let transaction = buffer
2737                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
2738                    .await?;
2739                buffer.update(&mut cx, |buffer, cx| {
2740                    if let Some(transaction) = transaction {
2741                        if !push_to_history {
2742                            buffer.forget_transaction(transaction.id);
2743                        }
2744                        project_transaction.0.insert(cx.handle(), transaction);
2745                    }
2746                });
2747            }
2748
2749            Ok(project_transaction)
2750        })
2751    }
2752
2753    pub fn format(
2754        &self,
2755        buffers: HashSet<ModelHandle<Buffer>>,
2756        push_to_history: bool,
2757        trigger: FormatTrigger,
2758        cx: &mut ModelContext<Project>,
2759    ) -> Task<Result<ProjectTransaction>> {
2760        let mut local_buffers = Vec::new();
2761        let mut remote_buffers = None;
2762        for buffer_handle in buffers {
2763            let buffer = buffer_handle.read(cx);
2764            if let Some(file) = File::from_dyn(buffer.file()) {
2765                if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
2766                    if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
2767                        local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
2768                    }
2769                } else {
2770                    remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2771                }
2772            } else {
2773                return Task::ready(Ok(Default::default()));
2774            }
2775        }
2776
2777        let remote_buffers = self.remote_id().zip(remote_buffers);
2778        let client = self.client.clone();
2779
2780        cx.spawn(|this, mut cx| async move {
2781            let mut project_transaction = ProjectTransaction::default();
2782
2783            if let Some((project_id, remote_buffers)) = remote_buffers {
2784                let response = client
2785                    .request(proto::FormatBuffers {
2786                        project_id,
2787                        trigger: trigger as i32,
2788                        buffer_ids: remote_buffers
2789                            .iter()
2790                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2791                            .collect(),
2792                    })
2793                    .await?
2794                    .transaction
2795                    .ok_or_else(|| anyhow!("missing transaction"))?;
2796                project_transaction = this
2797                    .update(&mut cx, |this, cx| {
2798                        this.deserialize_project_transaction(response, push_to_history, cx)
2799                    })
2800                    .await?;
2801            }
2802
2803            // Do not allow multiple concurrent formatting requests for the
2804            // same buffer.
2805            this.update(&mut cx, |this, _| {
2806                local_buffers
2807                    .retain(|(buffer, _, _)| this.buffers_being_formatted.insert(buffer.id()));
2808            });
2809            let _cleanup = defer({
2810                let this = this.clone();
2811                let mut cx = cx.clone();
2812                let local_buffers = &local_buffers;
2813                move || {
2814                    this.update(&mut cx, |this, _| {
2815                        for (buffer, _, _) in local_buffers {
2816                            this.buffers_being_formatted.remove(&buffer.id());
2817                        }
2818                    });
2819                }
2820            });
2821
2822            for (buffer, buffer_abs_path, language_server) in &local_buffers {
2823                let (format_on_save, formatter, tab_size) = buffer.read_with(&cx, |buffer, cx| {
2824                    let settings = cx.global::<Settings>();
2825                    let language_name = buffer.language().map(|language| language.name());
2826                    (
2827                        settings.format_on_save(language_name.as_deref()),
2828                        settings.formatter(language_name.as_deref()),
2829                        settings.tab_size(language_name.as_deref()),
2830                    )
2831                });
2832
2833                let transaction = match (formatter, format_on_save) {
2834                    (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => continue,
2835
2836                    (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
2837                    | (_, FormatOnSave::LanguageServer) => Self::format_via_lsp(
2838                        &this,
2839                        &buffer,
2840                        &buffer_abs_path,
2841                        &language_server,
2842                        tab_size,
2843                        &mut cx,
2844                    )
2845                    .await
2846                    .context("failed to format via language server")?,
2847
2848                    (
2849                        Formatter::External { command, arguments },
2850                        FormatOnSave::On | FormatOnSave::Off,
2851                    )
2852                    | (_, FormatOnSave::External { command, arguments }) => {
2853                        Self::format_via_external_command(
2854                            &buffer,
2855                            &buffer_abs_path,
2856                            &command,
2857                            &arguments,
2858                            &mut cx,
2859                        )
2860                        .await
2861                        .context(format!(
2862                            "failed to format via external command {:?}",
2863                            command
2864                        ))?
2865                    }
2866                };
2867
2868                if let Some(transaction) = transaction {
2869                    if !push_to_history {
2870                        buffer.update(&mut cx, |buffer, _| {
2871                            buffer.forget_transaction(transaction.id)
2872                        });
2873                    }
2874                    project_transaction.0.insert(buffer.clone(), transaction);
2875                }
2876            }
2877
2878            Ok(project_transaction)
2879        })
2880    }
2881
2882    async fn format_via_lsp(
2883        this: &ModelHandle<Self>,
2884        buffer: &ModelHandle<Buffer>,
2885        abs_path: &Path,
2886        language_server: &Arc<LanguageServer>,
2887        tab_size: NonZeroU32,
2888        cx: &mut AsyncAppContext,
2889    ) -> Result<Option<Transaction>> {
2890        let text_document =
2891            lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
2892        let capabilities = &language_server.capabilities();
2893        let lsp_edits = if capabilities
2894            .document_formatting_provider
2895            .as_ref()
2896            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2897        {
2898            language_server
2899                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
2900                    text_document,
2901                    options: lsp::FormattingOptions {
2902                        tab_size: tab_size.into(),
2903                        insert_spaces: true,
2904                        insert_final_newline: Some(true),
2905                        ..Default::default()
2906                    },
2907                    work_done_progress_params: Default::default(),
2908                })
2909                .await?
2910        } else if capabilities
2911            .document_range_formatting_provider
2912            .as_ref()
2913            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2914        {
2915            let buffer_start = lsp::Position::new(0, 0);
2916            let buffer_end =
2917                buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
2918            language_server
2919                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
2920                    text_document,
2921                    range: lsp::Range::new(buffer_start, buffer_end),
2922                    options: lsp::FormattingOptions {
2923                        tab_size: tab_size.into(),
2924                        insert_spaces: true,
2925                        insert_final_newline: Some(true),
2926                        ..Default::default()
2927                    },
2928                    work_done_progress_params: Default::default(),
2929                })
2930                .await?
2931        } else {
2932            None
2933        };
2934
2935        if let Some(lsp_edits) = lsp_edits {
2936            let edits = this
2937                .update(cx, |this, cx| {
2938                    this.edits_from_lsp(buffer, lsp_edits, None, cx)
2939                })
2940                .await?;
2941            buffer.update(cx, |buffer, cx| {
2942                buffer.finalize_last_transaction();
2943                buffer.start_transaction();
2944                for (range, text) in edits {
2945                    buffer.edit([(range, text)], None, cx);
2946                }
2947                if buffer.end_transaction(cx).is_some() {
2948                    let transaction = buffer.finalize_last_transaction().unwrap().clone();
2949                    Ok(Some(transaction))
2950                } else {
2951                    Ok(None)
2952                }
2953            })
2954        } else {
2955            Ok(None)
2956        }
2957    }
2958
2959    async fn format_via_external_command(
2960        buffer: &ModelHandle<Buffer>,
2961        buffer_abs_path: &Path,
2962        command: &str,
2963        arguments: &[String],
2964        cx: &mut AsyncAppContext,
2965    ) -> Result<Option<Transaction>> {
2966        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
2967            let file = File::from_dyn(buffer.file())?;
2968            let worktree = file.worktree.read(cx).as_local()?;
2969            let mut worktree_path = worktree.abs_path().to_path_buf();
2970            if worktree.root_entry()?.is_file() {
2971                worktree_path.pop();
2972            }
2973            Some(worktree_path)
2974        });
2975
2976        if let Some(working_dir_path) = working_dir_path {
2977            let mut child =
2978                smol::process::Command::new(command)
2979                    .args(arguments.iter().map(|arg| {
2980                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
2981                    }))
2982                    .current_dir(&working_dir_path)
2983                    .stdin(smol::process::Stdio::piped())
2984                    .stdout(smol::process::Stdio::piped())
2985                    .stderr(smol::process::Stdio::piped())
2986                    .spawn()?;
2987            let stdin = child
2988                .stdin
2989                .as_mut()
2990                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
2991            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
2992            for chunk in text.chunks() {
2993                stdin.write_all(chunk.as_bytes()).await?;
2994            }
2995            stdin.flush().await?;
2996
2997            let output = child.output().await?;
2998            if !output.status.success() {
2999                return Err(anyhow!(
3000                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3001                    output.status.code(),
3002                    String::from_utf8_lossy(&output.stdout),
3003                    String::from_utf8_lossy(&output.stderr),
3004                ));
3005            }
3006
3007            let stdout = String::from_utf8(output.stdout)?;
3008            let diff = buffer
3009                .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3010                .await;
3011            Ok(buffer.update(cx, |buffer, cx| buffer.apply_diff(diff, cx).cloned()))
3012        } else {
3013            Ok(None)
3014        }
3015    }
3016
3017    pub fn definition<T: ToPointUtf16>(
3018        &self,
3019        buffer: &ModelHandle<Buffer>,
3020        position: T,
3021        cx: &mut ModelContext<Self>,
3022    ) -> Task<Result<Vec<LocationLink>>> {
3023        let position = position.to_point_utf16(buffer.read(cx));
3024        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3025    }
3026
3027    pub fn type_definition<T: ToPointUtf16>(
3028        &self,
3029        buffer: &ModelHandle<Buffer>,
3030        position: T,
3031        cx: &mut ModelContext<Self>,
3032    ) -> Task<Result<Vec<LocationLink>>> {
3033        let position = position.to_point_utf16(buffer.read(cx));
3034        self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3035    }
3036
3037    pub fn references<T: ToPointUtf16>(
3038        &self,
3039        buffer: &ModelHandle<Buffer>,
3040        position: T,
3041        cx: &mut ModelContext<Self>,
3042    ) -> Task<Result<Vec<Location>>> {
3043        let position = position.to_point_utf16(buffer.read(cx));
3044        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3045    }
3046
3047    pub fn document_highlights<T: ToPointUtf16>(
3048        &self,
3049        buffer: &ModelHandle<Buffer>,
3050        position: T,
3051        cx: &mut ModelContext<Self>,
3052    ) -> Task<Result<Vec<DocumentHighlight>>> {
3053        let position = position.to_point_utf16(buffer.read(cx));
3054        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3055    }
3056
3057    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3058        if self.is_local() {
3059            let mut requests = Vec::new();
3060            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3061                let worktree_id = *worktree_id;
3062                if let Some(worktree) = self
3063                    .worktree_for_id(worktree_id, cx)
3064                    .and_then(|worktree| worktree.read(cx).as_local())
3065                {
3066                    if let Some(LanguageServerState::Running {
3067                        adapter,
3068                        language,
3069                        server,
3070                    }) = self.language_servers.get(server_id)
3071                    {
3072                        let adapter = adapter.clone();
3073                        let language = language.clone();
3074                        let worktree_abs_path = worktree.abs_path().clone();
3075                        requests.push(
3076                            server
3077                                .request::<lsp::request::WorkspaceSymbol>(
3078                                    lsp::WorkspaceSymbolParams {
3079                                        query: query.to_string(),
3080                                        ..Default::default()
3081                                    },
3082                                )
3083                                .log_err()
3084                                .map(move |response| {
3085                                    (
3086                                        adapter,
3087                                        language,
3088                                        worktree_id,
3089                                        worktree_abs_path,
3090                                        response.unwrap_or_default(),
3091                                    )
3092                                }),
3093                        );
3094                    }
3095                }
3096            }
3097
3098            cx.spawn_weak(|this, cx| async move {
3099                let responses = futures::future::join_all(requests).await;
3100                let this = if let Some(this) = this.upgrade(&cx) {
3101                    this
3102                } else {
3103                    return Ok(Default::default());
3104                };
3105                let symbols = this.read_with(&cx, |this, cx| {
3106                    let mut symbols = Vec::new();
3107                    for (
3108                        adapter,
3109                        adapter_language,
3110                        source_worktree_id,
3111                        worktree_abs_path,
3112                        response,
3113                    ) in responses
3114                    {
3115                        symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3116                            let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3117                            let mut worktree_id = source_worktree_id;
3118                            let path;
3119                            if let Some((worktree, rel_path)) =
3120                                this.find_local_worktree(&abs_path, cx)
3121                            {
3122                                worktree_id = worktree.read(cx).id();
3123                                path = rel_path;
3124                            } else {
3125                                path = relativize_path(&worktree_abs_path, &abs_path);
3126                            }
3127
3128                            let project_path = ProjectPath {
3129                                worktree_id,
3130                                path: path.into(),
3131                            };
3132                            let signature = this.symbol_signature(&project_path);
3133                            let language = this
3134                                .languages
3135                                .select_language(&project_path.path)
3136                                .unwrap_or(adapter_language.clone());
3137                            let language_server_name = adapter.name.clone();
3138                            Some(async move {
3139                                let label = language
3140                                    .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3141                                    .await;
3142
3143                                Symbol {
3144                                    language_server_name,
3145                                    source_worktree_id,
3146                                    path: project_path,
3147                                    label: label.unwrap_or_else(|| {
3148                                        CodeLabel::plain(lsp_symbol.name.clone(), None)
3149                                    }),
3150                                    kind: lsp_symbol.kind,
3151                                    name: lsp_symbol.name,
3152                                    range: range_from_lsp(lsp_symbol.location.range),
3153                                    signature,
3154                                }
3155                            })
3156                        }));
3157                    }
3158                    symbols
3159                });
3160                Ok(futures::future::join_all(symbols).await)
3161            })
3162        } else if let Some(project_id) = self.remote_id() {
3163            let request = self.client.request(proto::GetProjectSymbols {
3164                project_id,
3165                query: query.to_string(),
3166            });
3167            cx.spawn_weak(|this, cx| async move {
3168                let response = request.await?;
3169                let mut symbols = Vec::new();
3170                if let Some(this) = this.upgrade(&cx) {
3171                    let new_symbols = this.read_with(&cx, |this, _| {
3172                        response
3173                            .symbols
3174                            .into_iter()
3175                            .map(|symbol| this.deserialize_symbol(symbol))
3176                            .collect::<Vec<_>>()
3177                    });
3178                    symbols = futures::future::join_all(new_symbols)
3179                        .await
3180                        .into_iter()
3181                        .filter_map(|symbol| symbol.log_err())
3182                        .collect::<Vec<_>>();
3183                }
3184                Ok(symbols)
3185            })
3186        } else {
3187            Task::ready(Ok(Default::default()))
3188        }
3189    }
3190
3191    pub fn open_buffer_for_symbol(
3192        &mut self,
3193        symbol: &Symbol,
3194        cx: &mut ModelContext<Self>,
3195    ) -> Task<Result<ModelHandle<Buffer>>> {
3196        if self.is_local() {
3197            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3198                symbol.source_worktree_id,
3199                symbol.language_server_name.clone(),
3200            )) {
3201                *id
3202            } else {
3203                return Task::ready(Err(anyhow!(
3204                    "language server for worktree and language not found"
3205                )));
3206            };
3207
3208            let worktree_abs_path = if let Some(worktree_abs_path) = self
3209                .worktree_for_id(symbol.path.worktree_id, cx)
3210                .and_then(|worktree| worktree.read(cx).as_local())
3211                .map(|local_worktree| local_worktree.abs_path())
3212            {
3213                worktree_abs_path
3214            } else {
3215                return Task::ready(Err(anyhow!("worktree not found for symbol")));
3216            };
3217            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3218            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3219                uri
3220            } else {
3221                return Task::ready(Err(anyhow!("invalid symbol path")));
3222            };
3223
3224            self.open_local_buffer_via_lsp(
3225                symbol_uri,
3226                language_server_id,
3227                symbol.language_server_name.clone(),
3228                cx,
3229            )
3230        } else if let Some(project_id) = self.remote_id() {
3231            let request = self.client.request(proto::OpenBufferForSymbol {
3232                project_id,
3233                symbol: Some(serialize_symbol(symbol)),
3234            });
3235            cx.spawn(|this, mut cx| async move {
3236                let response = request.await?;
3237                this.update(&mut cx, |this, cx| {
3238                    this.wait_for_buffer(response.buffer_id, cx)
3239                })
3240                .await
3241            })
3242        } else {
3243            Task::ready(Err(anyhow!("project does not have a remote id")))
3244        }
3245    }
3246
3247    pub fn hover<T: ToPointUtf16>(
3248        &self,
3249        buffer: &ModelHandle<Buffer>,
3250        position: T,
3251        cx: &mut ModelContext<Self>,
3252    ) -> Task<Result<Option<Hover>>> {
3253        let position = position.to_point_utf16(buffer.read(cx));
3254        self.request_lsp(buffer.clone(), GetHover { position }, cx)
3255    }
3256
3257    pub fn completions<T: ToPointUtf16>(
3258        &self,
3259        source_buffer_handle: &ModelHandle<Buffer>,
3260        position: T,
3261        cx: &mut ModelContext<Self>,
3262    ) -> Task<Result<Vec<Completion>>> {
3263        let source_buffer_handle = source_buffer_handle.clone();
3264        let source_buffer = source_buffer_handle.read(cx);
3265        let buffer_id = source_buffer.remote_id();
3266        let language = source_buffer.language().cloned();
3267        let worktree;
3268        let buffer_abs_path;
3269        if let Some(file) = File::from_dyn(source_buffer.file()) {
3270            worktree = file.worktree.clone();
3271            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3272        } else {
3273            return Task::ready(Ok(Default::default()));
3274        };
3275
3276        let position = position.to_point_utf16(source_buffer);
3277        let anchor = source_buffer.anchor_after(position);
3278
3279        if worktree.read(cx).as_local().is_some() {
3280            let buffer_abs_path = buffer_abs_path.unwrap();
3281            let lang_server =
3282                if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3283                    server.clone()
3284                } else {
3285                    return Task::ready(Ok(Default::default()));
3286                };
3287
3288            cx.spawn(|_, cx| async move {
3289                let completions = lang_server
3290                    .request::<lsp::request::Completion>(lsp::CompletionParams {
3291                        text_document_position: lsp::TextDocumentPositionParams::new(
3292                            lsp::TextDocumentIdentifier::new(
3293                                lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3294                            ),
3295                            point_to_lsp(position),
3296                        ),
3297                        context: Default::default(),
3298                        work_done_progress_params: Default::default(),
3299                        partial_result_params: Default::default(),
3300                    })
3301                    .await
3302                    .context("lsp completion request failed")?;
3303
3304                let completions = if let Some(completions) = completions {
3305                    match completions {
3306                        lsp::CompletionResponse::Array(completions) => completions,
3307                        lsp::CompletionResponse::List(list) => list.items,
3308                    }
3309                } else {
3310                    Default::default()
3311                };
3312
3313                let completions = source_buffer_handle.read_with(&cx, |this, _| {
3314                    let snapshot = this.snapshot();
3315                    let clipped_position = this.clip_point_utf16(position, Bias::Left);
3316                    let mut range_for_token = None;
3317                    completions.into_iter().filter_map(move |lsp_completion| {
3318                        // For now, we can only handle additional edits if they are returned
3319                        // when resolving the completion, not if they are present initially.
3320                        if lsp_completion
3321                            .additional_text_edits
3322                            .as_ref()
3323                            .map_or(false, |edits| !edits.is_empty())
3324                        {
3325                            return None;
3326                        }
3327
3328                        let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref() {
3329                            // If the language server provides a range to overwrite, then
3330                            // check that the range is valid.
3331                            Some(lsp::CompletionTextEdit::Edit(edit)) => {
3332                                let range = range_from_lsp(edit.range);
3333                                let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3334                                let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3335                                if start != range.start || end != range.end {
3336                                    log::info!("completion out of expected range");
3337                                    return None;
3338                                }
3339                                (
3340                                    snapshot.anchor_before(start)..snapshot.anchor_after(end),
3341                                    edit.new_text.clone(),
3342                                )
3343                            }
3344                            // If the language server does not provide a range, then infer
3345                            // the range based on the syntax tree.
3346                            None => {
3347                                if position != clipped_position {
3348                                    log::info!("completion out of expected range");
3349                                    return None;
3350                                }
3351                                let Range { start, end } = range_for_token
3352                                    .get_or_insert_with(|| {
3353                                        let offset = position.to_offset(&snapshot);
3354                                        let (range, kind) = snapshot.surrounding_word(offset);
3355                                        if kind == Some(CharKind::Word) {
3356                                            range
3357                                        } else {
3358                                            offset..offset
3359                                        }
3360                                    })
3361                                    .clone();
3362                                let text = lsp_completion
3363                                    .insert_text
3364                                    .as_ref()
3365                                    .unwrap_or(&lsp_completion.label)
3366                                    .clone();
3367                                (
3368                                    snapshot.anchor_before(start)..snapshot.anchor_after(end),
3369                                    text,
3370                                )
3371                            }
3372                            Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3373                                log::info!("unsupported insert/replace completion");
3374                                return None;
3375                            }
3376                        };
3377
3378                        LineEnding::normalize(&mut new_text);
3379                        let language = language.clone();
3380                        Some(async move {
3381                            let label = if let Some(language) = language {
3382                                language.label_for_completion(&lsp_completion).await
3383                            } else {
3384                                None
3385                            };
3386                            Completion {
3387                                old_range,
3388                                new_text,
3389                                label: label.unwrap_or_else(|| {
3390                                    CodeLabel::plain(
3391                                        lsp_completion.label.clone(),
3392                                        lsp_completion.filter_text.as_deref(),
3393                                    )
3394                                }),
3395                                lsp_completion,
3396                            }
3397                        })
3398                    })
3399                });
3400
3401                Ok(futures::future::join_all(completions).await)
3402            })
3403        } else if let Some(project_id) = self.remote_id() {
3404            let rpc = self.client.clone();
3405            let message = proto::GetCompletions {
3406                project_id,
3407                buffer_id,
3408                position: Some(language::proto::serialize_anchor(&anchor)),
3409                version: serialize_version(&source_buffer.version()),
3410            };
3411            cx.spawn_weak(|this, mut cx| async move {
3412                let response = rpc.request(message).await?;
3413
3414                if this
3415                    .upgrade(&cx)
3416                    .ok_or_else(|| anyhow!("project was dropped"))?
3417                    .read_with(&cx, |this, _| this.is_read_only())
3418                {
3419                    return Err(anyhow!(
3420                        "failed to get completions: project was disconnected"
3421                    ));
3422                } else {
3423                    source_buffer_handle
3424                        .update(&mut cx, |buffer, _| {
3425                            buffer.wait_for_version(deserialize_version(response.version))
3426                        })
3427                        .await;
3428
3429                    let completions = response.completions.into_iter().map(|completion| {
3430                        language::proto::deserialize_completion(completion, language.clone())
3431                    });
3432                    futures::future::try_join_all(completions).await
3433                }
3434            })
3435        } else {
3436            Task::ready(Ok(Default::default()))
3437        }
3438    }
3439
3440    pub fn apply_additional_edits_for_completion(
3441        &self,
3442        buffer_handle: ModelHandle<Buffer>,
3443        completion: Completion,
3444        push_to_history: bool,
3445        cx: &mut ModelContext<Self>,
3446    ) -> Task<Result<Option<Transaction>>> {
3447        let buffer = buffer_handle.read(cx);
3448        let buffer_id = buffer.remote_id();
3449
3450        if self.is_local() {
3451            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3452            {
3453                server.clone()
3454            } else {
3455                return Task::ready(Ok(Default::default()));
3456            };
3457
3458            cx.spawn(|this, mut cx| async move {
3459                let resolved_completion = lang_server
3460                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3461                    .await?;
3462                if let Some(edits) = resolved_completion.additional_text_edits {
3463                    let edits = this
3464                        .update(&mut cx, |this, cx| {
3465                            this.edits_from_lsp(&buffer_handle, edits, None, cx)
3466                        })
3467                        .await?;
3468                    buffer_handle.update(&mut cx, |buffer, cx| {
3469                        buffer.finalize_last_transaction();
3470                        buffer.start_transaction();
3471                        for (range, text) in edits {
3472                            buffer.edit([(range, text)], None, cx);
3473                        }
3474                        let transaction = if buffer.end_transaction(cx).is_some() {
3475                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3476                            if !push_to_history {
3477                                buffer.forget_transaction(transaction.id);
3478                            }
3479                            Some(transaction)
3480                        } else {
3481                            None
3482                        };
3483                        Ok(transaction)
3484                    })
3485                } else {
3486                    Ok(None)
3487                }
3488            })
3489        } else if let Some(project_id) = self.remote_id() {
3490            let client = self.client.clone();
3491            cx.spawn(|_, mut cx| async move {
3492                let response = client
3493                    .request(proto::ApplyCompletionAdditionalEdits {
3494                        project_id,
3495                        buffer_id,
3496                        completion: Some(language::proto::serialize_completion(&completion)),
3497                    })
3498                    .await?;
3499
3500                if let Some(transaction) = response.transaction {
3501                    let transaction = language::proto::deserialize_transaction(transaction)?;
3502                    buffer_handle
3503                        .update(&mut cx, |buffer, _| {
3504                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3505                        })
3506                        .await;
3507                    if push_to_history {
3508                        buffer_handle.update(&mut cx, |buffer, _| {
3509                            buffer.push_transaction(transaction.clone(), Instant::now());
3510                        });
3511                    }
3512                    Ok(Some(transaction))
3513                } else {
3514                    Ok(None)
3515                }
3516            })
3517        } else {
3518            Task::ready(Err(anyhow!("project does not have a remote id")))
3519        }
3520    }
3521
3522    pub fn code_actions<T: Clone + ToOffset>(
3523        &self,
3524        buffer_handle: &ModelHandle<Buffer>,
3525        range: Range<T>,
3526        cx: &mut ModelContext<Self>,
3527    ) -> Task<Result<Vec<CodeAction>>> {
3528        let buffer_handle = buffer_handle.clone();
3529        let buffer = buffer_handle.read(cx);
3530        let snapshot = buffer.snapshot();
3531        let relevant_diagnostics = snapshot
3532            .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3533            .map(|entry| entry.to_lsp_diagnostic_stub())
3534            .collect();
3535        let buffer_id = buffer.remote_id();
3536        let worktree;
3537        let buffer_abs_path;
3538        if let Some(file) = File::from_dyn(buffer.file()) {
3539            worktree = file.worktree.clone();
3540            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3541        } else {
3542            return Task::ready(Ok(Default::default()));
3543        };
3544        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3545
3546        if worktree.read(cx).as_local().is_some() {
3547            let buffer_abs_path = buffer_abs_path.unwrap();
3548            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3549            {
3550                server.clone()
3551            } else {
3552                return Task::ready(Ok(Default::default()));
3553            };
3554
3555            let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3556            cx.foreground().spawn(async move {
3557                if lang_server.capabilities().code_action_provider.is_none() {
3558                    return Ok(Default::default());
3559                }
3560
3561                Ok(lang_server
3562                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3563                        text_document: lsp::TextDocumentIdentifier::new(
3564                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3565                        ),
3566                        range: lsp_range,
3567                        work_done_progress_params: Default::default(),
3568                        partial_result_params: Default::default(),
3569                        context: lsp::CodeActionContext {
3570                            diagnostics: relevant_diagnostics,
3571                            only: None,
3572                        },
3573                    })
3574                    .await?
3575                    .unwrap_or_default()
3576                    .into_iter()
3577                    .filter_map(|entry| {
3578                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3579                            Some(CodeAction {
3580                                range: range.clone(),
3581                                lsp_action,
3582                            })
3583                        } else {
3584                            None
3585                        }
3586                    })
3587                    .collect())
3588            })
3589        } else if let Some(project_id) = self.remote_id() {
3590            let rpc = self.client.clone();
3591            let version = buffer.version();
3592            cx.spawn_weak(|this, mut cx| async move {
3593                let response = rpc
3594                    .request(proto::GetCodeActions {
3595                        project_id,
3596                        buffer_id,
3597                        start: Some(language::proto::serialize_anchor(&range.start)),
3598                        end: Some(language::proto::serialize_anchor(&range.end)),
3599                        version: serialize_version(&version),
3600                    })
3601                    .await?;
3602
3603                if this
3604                    .upgrade(&cx)
3605                    .ok_or_else(|| anyhow!("project was dropped"))?
3606                    .read_with(&cx, |this, _| this.is_read_only())
3607                {
3608                    return Err(anyhow!(
3609                        "failed to get code actions: project was disconnected"
3610                    ));
3611                } else {
3612                    buffer_handle
3613                        .update(&mut cx, |buffer, _| {
3614                            buffer.wait_for_version(deserialize_version(response.version))
3615                        })
3616                        .await;
3617
3618                    response
3619                        .actions
3620                        .into_iter()
3621                        .map(language::proto::deserialize_code_action)
3622                        .collect()
3623                }
3624            })
3625        } else {
3626            Task::ready(Ok(Default::default()))
3627        }
3628    }
3629
3630    pub fn apply_code_action(
3631        &self,
3632        buffer_handle: ModelHandle<Buffer>,
3633        mut action: CodeAction,
3634        push_to_history: bool,
3635        cx: &mut ModelContext<Self>,
3636    ) -> Task<Result<ProjectTransaction>> {
3637        if self.is_local() {
3638            let buffer = buffer_handle.read(cx);
3639            let (lsp_adapter, lang_server) =
3640                if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3641                    (adapter.clone(), server.clone())
3642                } else {
3643                    return Task::ready(Ok(Default::default()));
3644                };
3645            let range = action.range.to_point_utf16(buffer);
3646
3647            cx.spawn(|this, mut cx| async move {
3648                if let Some(lsp_range) = action
3649                    .lsp_action
3650                    .data
3651                    .as_mut()
3652                    .and_then(|d| d.get_mut("codeActionParams"))
3653                    .and_then(|d| d.get_mut("range"))
3654                {
3655                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3656                    action.lsp_action = lang_server
3657                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3658                        .await?;
3659                } else {
3660                    let actions = this
3661                        .update(&mut cx, |this, cx| {
3662                            this.code_actions(&buffer_handle, action.range, cx)
3663                        })
3664                        .await?;
3665                    action.lsp_action = actions
3666                        .into_iter()
3667                        .find(|a| a.lsp_action.title == action.lsp_action.title)
3668                        .ok_or_else(|| anyhow!("code action is outdated"))?
3669                        .lsp_action;
3670                }
3671
3672                if let Some(edit) = action.lsp_action.edit {
3673                    if edit.changes.is_some() || edit.document_changes.is_some() {
3674                        return Self::deserialize_workspace_edit(
3675                            this,
3676                            edit,
3677                            push_to_history,
3678                            lsp_adapter.clone(),
3679                            lang_server.clone(),
3680                            &mut cx,
3681                        )
3682                        .await;
3683                    }
3684                }
3685
3686                if let Some(command) = action.lsp_action.command {
3687                    this.update(&mut cx, |this, _| {
3688                        this.last_workspace_edits_by_language_server
3689                            .remove(&lang_server.server_id());
3690                    });
3691                    lang_server
3692                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3693                            command: command.command,
3694                            arguments: command.arguments.unwrap_or_default(),
3695                            ..Default::default()
3696                        })
3697                        .await?;
3698                    return Ok(this.update(&mut cx, |this, _| {
3699                        this.last_workspace_edits_by_language_server
3700                            .remove(&lang_server.server_id())
3701                            .unwrap_or_default()
3702                    }));
3703                }
3704
3705                Ok(ProjectTransaction::default())
3706            })
3707        } else if let Some(project_id) = self.remote_id() {
3708            let client = self.client.clone();
3709            let request = proto::ApplyCodeAction {
3710                project_id,
3711                buffer_id: buffer_handle.read(cx).remote_id(),
3712                action: Some(language::proto::serialize_code_action(&action)),
3713            };
3714            cx.spawn(|this, mut cx| async move {
3715                let response = client
3716                    .request(request)
3717                    .await?
3718                    .transaction
3719                    .ok_or_else(|| anyhow!("missing transaction"))?;
3720                this.update(&mut cx, |this, cx| {
3721                    this.deserialize_project_transaction(response, push_to_history, cx)
3722                })
3723                .await
3724            })
3725        } else {
3726            Task::ready(Err(anyhow!("project does not have a remote id")))
3727        }
3728    }
3729
3730    async fn deserialize_workspace_edit(
3731        this: ModelHandle<Self>,
3732        edit: lsp::WorkspaceEdit,
3733        push_to_history: bool,
3734        lsp_adapter: Arc<CachedLspAdapter>,
3735        language_server: Arc<LanguageServer>,
3736        cx: &mut AsyncAppContext,
3737    ) -> Result<ProjectTransaction> {
3738        let fs = this.read_with(cx, |this, _| this.fs.clone());
3739        let mut operations = Vec::new();
3740        if let Some(document_changes) = edit.document_changes {
3741            match document_changes {
3742                lsp::DocumentChanges::Edits(edits) => {
3743                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3744                }
3745                lsp::DocumentChanges::Operations(ops) => operations = ops,
3746            }
3747        } else if let Some(changes) = edit.changes {
3748            operations.extend(changes.into_iter().map(|(uri, edits)| {
3749                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3750                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3751                        uri,
3752                        version: None,
3753                    },
3754                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3755                })
3756            }));
3757        }
3758
3759        let mut project_transaction = ProjectTransaction::default();
3760        for operation in operations {
3761            match operation {
3762                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3763                    let abs_path = op
3764                        .uri
3765                        .to_file_path()
3766                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3767
3768                    if let Some(parent_path) = abs_path.parent() {
3769                        fs.create_dir(parent_path).await?;
3770                    }
3771                    if abs_path.ends_with("/") {
3772                        fs.create_dir(&abs_path).await?;
3773                    } else {
3774                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3775                            .await?;
3776                    }
3777                }
3778                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3779                    let source_abs_path = op
3780                        .old_uri
3781                        .to_file_path()
3782                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3783                    let target_abs_path = op
3784                        .new_uri
3785                        .to_file_path()
3786                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3787                    fs.rename(
3788                        &source_abs_path,
3789                        &target_abs_path,
3790                        op.options.map(Into::into).unwrap_or_default(),
3791                    )
3792                    .await?;
3793                }
3794                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3795                    let abs_path = op
3796                        .uri
3797                        .to_file_path()
3798                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3799                    let options = op.options.map(Into::into).unwrap_or_default();
3800                    if abs_path.ends_with("/") {
3801                        fs.remove_dir(&abs_path, options).await?;
3802                    } else {
3803                        fs.remove_file(&abs_path, options).await?;
3804                    }
3805                }
3806                lsp::DocumentChangeOperation::Edit(op) => {
3807                    let buffer_to_edit = this
3808                        .update(cx, |this, cx| {
3809                            this.open_local_buffer_via_lsp(
3810                                op.text_document.uri,
3811                                language_server.server_id(),
3812                                lsp_adapter.name.clone(),
3813                                cx,
3814                            )
3815                        })
3816                        .await?;
3817
3818                    let edits = this
3819                        .update(cx, |this, cx| {
3820                            let edits = op.edits.into_iter().map(|edit| match edit {
3821                                lsp::OneOf::Left(edit) => edit,
3822                                lsp::OneOf::Right(edit) => edit.text_edit,
3823                            });
3824                            this.edits_from_lsp(
3825                                &buffer_to_edit,
3826                                edits,
3827                                op.text_document.version,
3828                                cx,
3829                            )
3830                        })
3831                        .await?;
3832
3833                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3834                        buffer.finalize_last_transaction();
3835                        buffer.start_transaction();
3836                        for (range, text) in edits {
3837                            buffer.edit([(range, text)], None, cx);
3838                        }
3839                        let transaction = if buffer.end_transaction(cx).is_some() {
3840                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3841                            if !push_to_history {
3842                                buffer.forget_transaction(transaction.id);
3843                            }
3844                            Some(transaction)
3845                        } else {
3846                            None
3847                        };
3848
3849                        transaction
3850                    });
3851                    if let Some(transaction) = transaction {
3852                        project_transaction.0.insert(buffer_to_edit, transaction);
3853                    }
3854                }
3855            }
3856        }
3857
3858        Ok(project_transaction)
3859    }
3860
3861    pub fn prepare_rename<T: ToPointUtf16>(
3862        &self,
3863        buffer: ModelHandle<Buffer>,
3864        position: T,
3865        cx: &mut ModelContext<Self>,
3866    ) -> Task<Result<Option<Range<Anchor>>>> {
3867        let position = position.to_point_utf16(buffer.read(cx));
3868        self.request_lsp(buffer, PrepareRename { position }, cx)
3869    }
3870
3871    pub fn perform_rename<T: ToPointUtf16>(
3872        &self,
3873        buffer: ModelHandle<Buffer>,
3874        position: T,
3875        new_name: String,
3876        push_to_history: bool,
3877        cx: &mut ModelContext<Self>,
3878    ) -> Task<Result<ProjectTransaction>> {
3879        let position = position.to_point_utf16(buffer.read(cx));
3880        self.request_lsp(
3881            buffer,
3882            PerformRename {
3883                position,
3884                new_name,
3885                push_to_history,
3886            },
3887            cx,
3888        )
3889    }
3890
3891    #[allow(clippy::type_complexity)]
3892    pub fn search(
3893        &self,
3894        query: SearchQuery,
3895        cx: &mut ModelContext<Self>,
3896    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
3897        if self.is_local() {
3898            let snapshots = self
3899                .visible_worktrees(cx)
3900                .filter_map(|tree| {
3901                    let tree = tree.read(cx).as_local()?;
3902                    Some(tree.snapshot())
3903                })
3904                .collect::<Vec<_>>();
3905
3906            let background = cx.background().clone();
3907            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
3908            if path_count == 0 {
3909                return Task::ready(Ok(Default::default()));
3910            }
3911            let workers = background.num_cpus().min(path_count);
3912            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
3913            cx.background()
3914                .spawn({
3915                    let fs = self.fs.clone();
3916                    let background = cx.background().clone();
3917                    let query = query.clone();
3918                    async move {
3919                        let fs = &fs;
3920                        let query = &query;
3921                        let matching_paths_tx = &matching_paths_tx;
3922                        let paths_per_worker = (path_count + workers - 1) / workers;
3923                        let snapshots = &snapshots;
3924                        background
3925                            .scoped(|scope| {
3926                                for worker_ix in 0..workers {
3927                                    let worker_start_ix = worker_ix * paths_per_worker;
3928                                    let worker_end_ix = worker_start_ix + paths_per_worker;
3929                                    scope.spawn(async move {
3930                                        let mut snapshot_start_ix = 0;
3931                                        let mut abs_path = PathBuf::new();
3932                                        for snapshot in snapshots {
3933                                            let snapshot_end_ix =
3934                                                snapshot_start_ix + snapshot.visible_file_count();
3935                                            if worker_end_ix <= snapshot_start_ix {
3936                                                break;
3937                                            } else if worker_start_ix > snapshot_end_ix {
3938                                                snapshot_start_ix = snapshot_end_ix;
3939                                                continue;
3940                                            } else {
3941                                                let start_in_snapshot = worker_start_ix
3942                                                    .saturating_sub(snapshot_start_ix);
3943                                                let end_in_snapshot =
3944                                                    cmp::min(worker_end_ix, snapshot_end_ix)
3945                                                        - snapshot_start_ix;
3946
3947                                                for entry in snapshot
3948                                                    .files(false, start_in_snapshot)
3949                                                    .take(end_in_snapshot - start_in_snapshot)
3950                                                {
3951                                                    if matching_paths_tx.is_closed() {
3952                                                        break;
3953                                                    }
3954
3955                                                    abs_path.clear();
3956                                                    abs_path.push(&snapshot.abs_path());
3957                                                    abs_path.push(&entry.path);
3958                                                    let matches = if let Some(file) =
3959                                                        fs.open_sync(&abs_path).await.log_err()
3960                                                    {
3961                                                        query.detect(file).unwrap_or(false)
3962                                                    } else {
3963                                                        false
3964                                                    };
3965
3966                                                    if matches {
3967                                                        let project_path =
3968                                                            (snapshot.id(), entry.path.clone());
3969                                                        if matching_paths_tx
3970                                                            .send(project_path)
3971                                                            .await
3972                                                            .is_err()
3973                                                        {
3974                                                            break;
3975                                                        }
3976                                                    }
3977                                                }
3978
3979                                                snapshot_start_ix = snapshot_end_ix;
3980                                            }
3981                                        }
3982                                    });
3983                                }
3984                            })
3985                            .await;
3986                    }
3987                })
3988                .detach();
3989
3990            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
3991            let open_buffers = self
3992                .opened_buffers
3993                .values()
3994                .filter_map(|b| b.upgrade(cx))
3995                .collect::<HashSet<_>>();
3996            cx.spawn(|this, cx| async move {
3997                for buffer in &open_buffers {
3998                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3999                    buffers_tx.send((buffer.clone(), snapshot)).await?;
4000                }
4001
4002                let open_buffers = Rc::new(RefCell::new(open_buffers));
4003                while let Some(project_path) = matching_paths_rx.next().await {
4004                    if buffers_tx.is_closed() {
4005                        break;
4006                    }
4007
4008                    let this = this.clone();
4009                    let open_buffers = open_buffers.clone();
4010                    let buffers_tx = buffers_tx.clone();
4011                    cx.spawn(|mut cx| async move {
4012                        if let Some(buffer) = this
4013                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4014                            .await
4015                            .log_err()
4016                        {
4017                            if open_buffers.borrow_mut().insert(buffer.clone()) {
4018                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4019                                buffers_tx.send((buffer, snapshot)).await?;
4020                            }
4021                        }
4022
4023                        Ok::<_, anyhow::Error>(())
4024                    })
4025                    .detach();
4026                }
4027
4028                Ok::<_, anyhow::Error>(())
4029            })
4030            .detach_and_log_err(cx);
4031
4032            let background = cx.background().clone();
4033            cx.background().spawn(async move {
4034                let query = &query;
4035                let mut matched_buffers = Vec::new();
4036                for _ in 0..workers {
4037                    matched_buffers.push(HashMap::default());
4038                }
4039                background
4040                    .scoped(|scope| {
4041                        for worker_matched_buffers in matched_buffers.iter_mut() {
4042                            let mut buffers_rx = buffers_rx.clone();
4043                            scope.spawn(async move {
4044                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
4045                                    let buffer_matches = query
4046                                        .search(snapshot.as_rope())
4047                                        .await
4048                                        .iter()
4049                                        .map(|range| {
4050                                            snapshot.anchor_before(range.start)
4051                                                ..snapshot.anchor_after(range.end)
4052                                        })
4053                                        .collect::<Vec<_>>();
4054                                    if !buffer_matches.is_empty() {
4055                                        worker_matched_buffers
4056                                            .insert(buffer.clone(), buffer_matches);
4057                                    }
4058                                }
4059                            });
4060                        }
4061                    })
4062                    .await;
4063                Ok(matched_buffers.into_iter().flatten().collect())
4064            })
4065        } else if let Some(project_id) = self.remote_id() {
4066            let request = self.client.request(query.to_proto(project_id));
4067            cx.spawn(|this, mut cx| async move {
4068                let response = request.await?;
4069                let mut result = HashMap::default();
4070                for location in response.locations {
4071                    let target_buffer = this
4072                        .update(&mut cx, |this, cx| {
4073                            this.wait_for_buffer(location.buffer_id, cx)
4074                        })
4075                        .await?;
4076                    let start = location
4077                        .start
4078                        .and_then(deserialize_anchor)
4079                        .ok_or_else(|| anyhow!("missing target start"))?;
4080                    let end = location
4081                        .end
4082                        .and_then(deserialize_anchor)
4083                        .ok_or_else(|| anyhow!("missing target end"))?;
4084                    result
4085                        .entry(target_buffer)
4086                        .or_insert(Vec::new())
4087                        .push(start..end)
4088                }
4089                Ok(result)
4090            })
4091        } else {
4092            Task::ready(Ok(Default::default()))
4093        }
4094    }
4095
4096    fn request_lsp<R: LspCommand>(
4097        &self,
4098        buffer_handle: ModelHandle<Buffer>,
4099        request: R,
4100        cx: &mut ModelContext<Self>,
4101    ) -> Task<Result<R::Response>>
4102    where
4103        <R::LspRequest as lsp::request::Request>::Result: Send,
4104    {
4105        let buffer = buffer_handle.read(cx);
4106        if self.is_local() {
4107            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4108            if let Some((file, language_server)) = file.zip(
4109                self.language_server_for_buffer(buffer, cx)
4110                    .map(|(_, server)| server.clone()),
4111            ) {
4112                let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4113                return cx.spawn(|this, cx| async move {
4114                    if !request.check_capabilities(language_server.capabilities()) {
4115                        return Ok(Default::default());
4116                    }
4117
4118                    let response = language_server
4119                        .request::<R::LspRequest>(lsp_params)
4120                        .await
4121                        .context("lsp request failed")?;
4122                    request
4123                        .response_from_lsp(response, this, buffer_handle, cx)
4124                        .await
4125                });
4126            }
4127        } else if let Some(project_id) = self.remote_id() {
4128            let rpc = self.client.clone();
4129            let message = request.to_proto(project_id, buffer);
4130            return cx.spawn(|this, cx| async move {
4131                let response = rpc.request(message).await?;
4132                if this.read_with(&cx, |this, _| this.is_read_only()) {
4133                    Err(anyhow!("disconnected before completing request"))
4134                } else {
4135                    request
4136                        .response_from_proto(response, this, buffer_handle, cx)
4137                        .await
4138                }
4139            });
4140        }
4141        Task::ready(Ok(Default::default()))
4142    }
4143
4144    pub fn find_or_create_local_worktree(
4145        &mut self,
4146        abs_path: impl AsRef<Path>,
4147        visible: bool,
4148        cx: &mut ModelContext<Self>,
4149    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4150        let abs_path = abs_path.as_ref();
4151        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4152            Task::ready(Ok((tree, relative_path)))
4153        } else {
4154            let worktree = self.create_local_worktree(abs_path, visible, cx);
4155            cx.foreground()
4156                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4157        }
4158    }
4159
4160    pub fn find_local_worktree(
4161        &self,
4162        abs_path: &Path,
4163        cx: &AppContext,
4164    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4165        for tree in &self.worktrees {
4166            if let Some(tree) = tree.upgrade(cx) {
4167                if let Some(relative_path) = tree
4168                    .read(cx)
4169                    .as_local()
4170                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4171                {
4172                    return Some((tree.clone(), relative_path.into()));
4173                }
4174            }
4175        }
4176        None
4177    }
4178
4179    pub fn is_shared(&self) -> bool {
4180        match &self.client_state {
4181            Some(ProjectClientState::Local { .. }) => true,
4182            _ => false,
4183        }
4184    }
4185
4186    fn create_local_worktree(
4187        &mut self,
4188        abs_path: impl AsRef<Path>,
4189        visible: bool,
4190        cx: &mut ModelContext<Self>,
4191    ) -> Task<Result<ModelHandle<Worktree>>> {
4192        let fs = self.fs.clone();
4193        let client = self.client.clone();
4194        let next_entry_id = self.next_entry_id.clone();
4195        let path: Arc<Path> = abs_path.as_ref().into();
4196        let task = self
4197            .loading_local_worktrees
4198            .entry(path.clone())
4199            .or_insert_with(|| {
4200                cx.spawn(|project, mut cx| {
4201                    async move {
4202                        let worktree = Worktree::local(
4203                            client.clone(),
4204                            path.clone(),
4205                            visible,
4206                            fs,
4207                            next_entry_id,
4208                            &mut cx,
4209                        )
4210                        .await;
4211                        project.update(&mut cx, |project, _| {
4212                            project.loading_local_worktrees.remove(&path);
4213                        });
4214                        let worktree = worktree?;
4215
4216                        project
4217                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))
4218                            .await;
4219
4220                        if let Some(project_id) =
4221                            project.read_with(&cx, |project, _| project.remote_id())
4222                        {
4223                            worktree
4224                                .update(&mut cx, |worktree, cx| {
4225                                    worktree.as_local_mut().unwrap().share(project_id, cx)
4226                                })
4227                                .await
4228                                .log_err();
4229                        }
4230
4231                        Ok(worktree)
4232                    }
4233                    .map_err(Arc::new)
4234                })
4235                .shared()
4236            })
4237            .clone();
4238        cx.foreground().spawn(async move {
4239            match task.await {
4240                Ok(worktree) => Ok(worktree),
4241                Err(err) => Err(anyhow!("{}", err)),
4242            }
4243        })
4244    }
4245
4246    pub fn remove_worktree(
4247        &mut self,
4248        id_to_remove: WorktreeId,
4249        cx: &mut ModelContext<Self>,
4250    ) -> impl Future<Output = ()> {
4251        self.worktrees.retain(|worktree| {
4252            if let Some(worktree) = worktree.upgrade(cx) {
4253                let id = worktree.read(cx).id();
4254                if id == id_to_remove {
4255                    cx.emit(Event::WorktreeRemoved(id));
4256                    false
4257                } else {
4258                    true
4259                }
4260            } else {
4261                false
4262            }
4263        });
4264        self.metadata_changed(cx)
4265    }
4266
4267    fn add_worktree(
4268        &mut self,
4269        worktree: &ModelHandle<Worktree>,
4270        cx: &mut ModelContext<Self>,
4271    ) -> impl Future<Output = ()> {
4272        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4273        if worktree.read(cx).is_local() {
4274            cx.subscribe(worktree, |this, worktree, event, cx| match event {
4275                worktree::Event::UpdatedEntries => this.update_local_worktree_buffers(worktree, cx),
4276                worktree::Event::UpdatedGitRepositories(updated_repos) => {
4277                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4278                }
4279            })
4280            .detach();
4281        }
4282
4283        let push_strong_handle = {
4284            let worktree = worktree.read(cx);
4285            self.is_shared() || worktree.is_visible() || worktree.is_remote()
4286        };
4287        if push_strong_handle {
4288            self.worktrees
4289                .push(WorktreeHandle::Strong(worktree.clone()));
4290        } else {
4291            self.worktrees
4292                .push(WorktreeHandle::Weak(worktree.downgrade()));
4293        }
4294
4295        cx.observe_release(worktree, |this, worktree, cx| {
4296            let _ = this.remove_worktree(worktree.id(), cx);
4297        })
4298        .detach();
4299
4300        cx.emit(Event::WorktreeAdded);
4301        self.metadata_changed(cx)
4302    }
4303
4304    fn update_local_worktree_buffers(
4305        &mut self,
4306        worktree_handle: ModelHandle<Worktree>,
4307        cx: &mut ModelContext<Self>,
4308    ) {
4309        let snapshot = worktree_handle.read(cx).snapshot();
4310        let mut buffers_to_delete = Vec::new();
4311        let mut renamed_buffers = Vec::new();
4312        for (buffer_id, buffer) in &self.opened_buffers {
4313            if let Some(buffer) = buffer.upgrade(cx) {
4314                buffer.update(cx, |buffer, cx| {
4315                    if let Some(old_file) = File::from_dyn(buffer.file()) {
4316                        if old_file.worktree != worktree_handle {
4317                            return;
4318                        }
4319
4320                        let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id)
4321                        {
4322                            File {
4323                                is_local: true,
4324                                entry_id: entry.id,
4325                                mtime: entry.mtime,
4326                                path: entry.path.clone(),
4327                                worktree: worktree_handle.clone(),
4328                                is_deleted: false,
4329                            }
4330                        } else if let Some(entry) =
4331                            snapshot.entry_for_path(old_file.path().as_ref())
4332                        {
4333                            File {
4334                                is_local: true,
4335                                entry_id: entry.id,
4336                                mtime: entry.mtime,
4337                                path: entry.path.clone(),
4338                                worktree: worktree_handle.clone(),
4339                                is_deleted: false,
4340                            }
4341                        } else {
4342                            File {
4343                                is_local: true,
4344                                entry_id: old_file.entry_id,
4345                                path: old_file.path().clone(),
4346                                mtime: old_file.mtime(),
4347                                worktree: worktree_handle.clone(),
4348                                is_deleted: true,
4349                            }
4350                        };
4351
4352                        let old_path = old_file.abs_path(cx);
4353                        if new_file.abs_path(cx) != old_path {
4354                            renamed_buffers.push((cx.handle(), old_path));
4355                        }
4356
4357                        if let Some(project_id) = self.remote_id() {
4358                            self.client
4359                                .send(proto::UpdateBufferFile {
4360                                    project_id,
4361                                    buffer_id: *buffer_id as u64,
4362                                    file: Some(new_file.to_proto()),
4363                                })
4364                                .log_err();
4365                        }
4366                        buffer.file_updated(Arc::new(new_file), cx).detach();
4367                    }
4368                });
4369            } else {
4370                buffers_to_delete.push(*buffer_id);
4371            }
4372        }
4373
4374        for buffer_id in buffers_to_delete {
4375            self.opened_buffers.remove(&buffer_id);
4376        }
4377
4378        for (buffer, old_path) in renamed_buffers {
4379            self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4380            self.assign_language_to_buffer(&buffer, cx);
4381            self.register_buffer_with_language_server(&buffer, cx);
4382        }
4383    }
4384
4385    fn update_local_worktree_buffers_git_repos(
4386        &mut self,
4387        worktree: ModelHandle<Worktree>,
4388        repos: &[GitRepositoryEntry],
4389        cx: &mut ModelContext<Self>,
4390    ) {
4391        for (_, buffer) in &self.opened_buffers {
4392            if let Some(buffer) = buffer.upgrade(cx) {
4393                let file = match File::from_dyn(buffer.read(cx).file()) {
4394                    Some(file) => file,
4395                    None => continue,
4396                };
4397                if file.worktree != worktree {
4398                    continue;
4399                }
4400
4401                let path = file.path().clone();
4402
4403                let repo = match repos.iter().find(|repo| repo.manages(&path)) {
4404                    Some(repo) => repo.clone(),
4405                    None => return,
4406                };
4407
4408                let relative_repo = match path.strip_prefix(repo.content_path) {
4409                    Ok(relative_repo) => relative_repo.to_owned(),
4410                    Err(_) => return,
4411                };
4412
4413                let remote_id = self.remote_id();
4414                let client = self.client.clone();
4415
4416                cx.spawn(|_, mut cx| async move {
4417                    let diff_base = cx
4418                        .background()
4419                        .spawn(async move { repo.repo.lock().load_index_text(&relative_repo) })
4420                        .await;
4421
4422                    let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4423                        buffer.set_diff_base(diff_base.clone(), cx);
4424                        buffer.remote_id()
4425                    });
4426
4427                    if let Some(project_id) = remote_id {
4428                        client
4429                            .send(proto::UpdateDiffBase {
4430                                project_id,
4431                                buffer_id: buffer_id as u64,
4432                                diff_base,
4433                            })
4434                            .log_err();
4435                    }
4436                })
4437                .detach();
4438            }
4439        }
4440    }
4441
4442    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4443        let new_active_entry = entry.and_then(|project_path| {
4444            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4445            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4446            Some(entry.id)
4447        });
4448        if new_active_entry != self.active_entry {
4449            self.active_entry = new_active_entry;
4450            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4451        }
4452    }
4453
4454    pub fn language_servers_running_disk_based_diagnostics(
4455        &self,
4456    ) -> impl Iterator<Item = usize> + '_ {
4457        self.language_server_statuses
4458            .iter()
4459            .filter_map(|(id, status)| {
4460                if status.has_pending_diagnostic_updates {
4461                    Some(*id)
4462                } else {
4463                    None
4464                }
4465            })
4466    }
4467
4468    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4469        let mut summary = DiagnosticSummary::default();
4470        for (_, path_summary) in self.diagnostic_summaries(cx) {
4471            summary.error_count += path_summary.error_count;
4472            summary.warning_count += path_summary.warning_count;
4473        }
4474        summary
4475    }
4476
4477    pub fn diagnostic_summaries<'a>(
4478        &'a self,
4479        cx: &'a AppContext,
4480    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4481        self.visible_worktrees(cx).flat_map(move |worktree| {
4482            let worktree = worktree.read(cx);
4483            let worktree_id = worktree.id();
4484            worktree
4485                .diagnostic_summaries()
4486                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4487        })
4488    }
4489
4490    pub fn disk_based_diagnostics_started(
4491        &mut self,
4492        language_server_id: usize,
4493        cx: &mut ModelContext<Self>,
4494    ) {
4495        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4496    }
4497
4498    pub fn disk_based_diagnostics_finished(
4499        &mut self,
4500        language_server_id: usize,
4501        cx: &mut ModelContext<Self>,
4502    ) {
4503        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4504    }
4505
4506    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4507        self.active_entry
4508    }
4509
4510    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4511        self.worktree_for_id(path.worktree_id, cx)?
4512            .read(cx)
4513            .entry_for_path(&path.path)
4514            .cloned()
4515    }
4516
4517    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4518        let worktree = self.worktree_for_entry(entry_id, cx)?;
4519        let worktree = worktree.read(cx);
4520        let worktree_id = worktree.id();
4521        let path = worktree.entry_for_id(entry_id)?.path.clone();
4522        Some(ProjectPath { worktree_id, path })
4523    }
4524
4525    // RPC message handlers
4526
4527    async fn handle_unshare_project(
4528        this: ModelHandle<Self>,
4529        _: TypedEnvelope<proto::UnshareProject>,
4530        _: Arc<Client>,
4531        mut cx: AsyncAppContext,
4532    ) -> Result<()> {
4533        this.update(&mut cx, |this, cx| {
4534            if this.is_local() {
4535                this.unshare(cx)?;
4536            } else {
4537                this.disconnected_from_host(cx);
4538            }
4539            Ok(())
4540        })
4541    }
4542
4543    async fn handle_add_collaborator(
4544        this: ModelHandle<Self>,
4545        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4546        _: Arc<Client>,
4547        mut cx: AsyncAppContext,
4548    ) -> Result<()> {
4549        let collaborator = envelope
4550            .payload
4551            .collaborator
4552            .take()
4553            .ok_or_else(|| anyhow!("empty collaborator"))?;
4554
4555        let collaborator = Collaborator::from_proto(collaborator);
4556        this.update(&mut cx, |this, cx| {
4557            this.collaborators
4558                .insert(collaborator.peer_id, collaborator);
4559            cx.notify();
4560        });
4561
4562        Ok(())
4563    }
4564
4565    async fn handle_remove_collaborator(
4566        this: ModelHandle<Self>,
4567        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4568        _: Arc<Client>,
4569        mut cx: AsyncAppContext,
4570    ) -> Result<()> {
4571        this.update(&mut cx, |this, cx| {
4572            let peer_id = PeerId(envelope.payload.peer_id);
4573            let replica_id = this
4574                .collaborators
4575                .remove(&peer_id)
4576                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4577                .replica_id;
4578            for buffer in this.opened_buffers.values() {
4579                if let Some(buffer) = buffer.upgrade(cx) {
4580                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4581                }
4582            }
4583            this.shared_buffers.remove(&peer_id);
4584
4585            cx.emit(Event::CollaboratorLeft(peer_id));
4586            cx.notify();
4587            Ok(())
4588        })
4589    }
4590
4591    async fn handle_update_project(
4592        this: ModelHandle<Self>,
4593        envelope: TypedEnvelope<proto::UpdateProject>,
4594        client: Arc<Client>,
4595        mut cx: AsyncAppContext,
4596    ) -> Result<()> {
4597        this.update(&mut cx, |this, cx| {
4598            let replica_id = this.replica_id();
4599            let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
4600
4601            let mut old_worktrees_by_id = this
4602                .worktrees
4603                .drain(..)
4604                .filter_map(|worktree| {
4605                    let worktree = worktree.upgrade(cx)?;
4606                    Some((worktree.read(cx).id(), worktree))
4607                })
4608                .collect::<HashMap<_, _>>();
4609
4610            for worktree in envelope.payload.worktrees {
4611                if let Some(old_worktree) =
4612                    old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
4613                {
4614                    this.worktrees.push(WorktreeHandle::Strong(old_worktree));
4615                } else {
4616                    let worktree =
4617                        Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
4618                    let _ = this.add_worktree(&worktree, cx);
4619                }
4620            }
4621
4622            let _ = this.metadata_changed(cx);
4623            for (id, _) in old_worktrees_by_id {
4624                cx.emit(Event::WorktreeRemoved(id));
4625            }
4626
4627            Ok(())
4628        })
4629    }
4630
4631    async fn handle_update_worktree(
4632        this: ModelHandle<Self>,
4633        envelope: TypedEnvelope<proto::UpdateWorktree>,
4634        _: Arc<Client>,
4635        mut cx: AsyncAppContext,
4636    ) -> Result<()> {
4637        this.update(&mut cx, |this, cx| {
4638            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4639            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4640                worktree.update(cx, |worktree, _| {
4641                    let worktree = worktree.as_remote_mut().unwrap();
4642                    worktree.update_from_remote(envelope.payload);
4643                });
4644            }
4645            Ok(())
4646        })
4647    }
4648
4649    async fn handle_create_project_entry(
4650        this: ModelHandle<Self>,
4651        envelope: TypedEnvelope<proto::CreateProjectEntry>,
4652        _: Arc<Client>,
4653        mut cx: AsyncAppContext,
4654    ) -> Result<proto::ProjectEntryResponse> {
4655        let worktree = this.update(&mut cx, |this, cx| {
4656            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4657            this.worktree_for_id(worktree_id, cx)
4658                .ok_or_else(|| anyhow!("worktree not found"))
4659        })?;
4660        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4661        let entry = worktree
4662            .update(&mut cx, |worktree, cx| {
4663                let worktree = worktree.as_local_mut().unwrap();
4664                let path = PathBuf::from(envelope.payload.path);
4665                worktree.create_entry(path, envelope.payload.is_directory, cx)
4666            })
4667            .await?;
4668        Ok(proto::ProjectEntryResponse {
4669            entry: Some((&entry).into()),
4670            worktree_scan_id: worktree_scan_id as u64,
4671        })
4672    }
4673
4674    async fn handle_rename_project_entry(
4675        this: ModelHandle<Self>,
4676        envelope: TypedEnvelope<proto::RenameProjectEntry>,
4677        _: Arc<Client>,
4678        mut cx: AsyncAppContext,
4679    ) -> Result<proto::ProjectEntryResponse> {
4680        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4681        let worktree = this.read_with(&cx, |this, cx| {
4682            this.worktree_for_entry(entry_id, cx)
4683                .ok_or_else(|| anyhow!("worktree not found"))
4684        })?;
4685        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4686        let entry = worktree
4687            .update(&mut cx, |worktree, cx| {
4688                let new_path = PathBuf::from(envelope.payload.new_path);
4689                worktree
4690                    .as_local_mut()
4691                    .unwrap()
4692                    .rename_entry(entry_id, new_path, cx)
4693                    .ok_or_else(|| anyhow!("invalid entry"))
4694            })?
4695            .await?;
4696        Ok(proto::ProjectEntryResponse {
4697            entry: Some((&entry).into()),
4698            worktree_scan_id: worktree_scan_id as u64,
4699        })
4700    }
4701
4702    async fn handle_copy_project_entry(
4703        this: ModelHandle<Self>,
4704        envelope: TypedEnvelope<proto::CopyProjectEntry>,
4705        _: Arc<Client>,
4706        mut cx: AsyncAppContext,
4707    ) -> Result<proto::ProjectEntryResponse> {
4708        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4709        let worktree = this.read_with(&cx, |this, cx| {
4710            this.worktree_for_entry(entry_id, cx)
4711                .ok_or_else(|| anyhow!("worktree not found"))
4712        })?;
4713        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4714        let entry = worktree
4715            .update(&mut cx, |worktree, cx| {
4716                let new_path = PathBuf::from(envelope.payload.new_path);
4717                worktree
4718                    .as_local_mut()
4719                    .unwrap()
4720                    .copy_entry(entry_id, new_path, cx)
4721                    .ok_or_else(|| anyhow!("invalid entry"))
4722            })?
4723            .await?;
4724        Ok(proto::ProjectEntryResponse {
4725            entry: Some((&entry).into()),
4726            worktree_scan_id: worktree_scan_id as u64,
4727        })
4728    }
4729
4730    async fn handle_delete_project_entry(
4731        this: ModelHandle<Self>,
4732        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4733        _: Arc<Client>,
4734        mut cx: AsyncAppContext,
4735    ) -> Result<proto::ProjectEntryResponse> {
4736        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4737        let worktree = this.read_with(&cx, |this, cx| {
4738            this.worktree_for_entry(entry_id, cx)
4739                .ok_or_else(|| anyhow!("worktree not found"))
4740        })?;
4741        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4742        worktree
4743            .update(&mut cx, |worktree, cx| {
4744                worktree
4745                    .as_local_mut()
4746                    .unwrap()
4747                    .delete_entry(entry_id, cx)
4748                    .ok_or_else(|| anyhow!("invalid entry"))
4749            })?
4750            .await?;
4751        Ok(proto::ProjectEntryResponse {
4752            entry: None,
4753            worktree_scan_id: worktree_scan_id as u64,
4754        })
4755    }
4756
4757    async fn handle_update_diagnostic_summary(
4758        this: ModelHandle<Self>,
4759        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4760        _: Arc<Client>,
4761        mut cx: AsyncAppContext,
4762    ) -> Result<()> {
4763        this.update(&mut cx, |this, cx| {
4764            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4765            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4766                if let Some(summary) = envelope.payload.summary {
4767                    let project_path = ProjectPath {
4768                        worktree_id,
4769                        path: Path::new(&summary.path).into(),
4770                    };
4771                    worktree.update(cx, |worktree, _| {
4772                        worktree
4773                            .as_remote_mut()
4774                            .unwrap()
4775                            .update_diagnostic_summary(project_path.path.clone(), &summary);
4776                    });
4777                    cx.emit(Event::DiagnosticsUpdated {
4778                        language_server_id: summary.language_server_id as usize,
4779                        path: project_path,
4780                    });
4781                }
4782            }
4783            Ok(())
4784        })
4785    }
4786
4787    async fn handle_start_language_server(
4788        this: ModelHandle<Self>,
4789        envelope: TypedEnvelope<proto::StartLanguageServer>,
4790        _: Arc<Client>,
4791        mut cx: AsyncAppContext,
4792    ) -> Result<()> {
4793        let server = envelope
4794            .payload
4795            .server
4796            .ok_or_else(|| anyhow!("invalid server"))?;
4797        this.update(&mut cx, |this, cx| {
4798            this.language_server_statuses.insert(
4799                server.id as usize,
4800                LanguageServerStatus {
4801                    name: server.name,
4802                    pending_work: Default::default(),
4803                    has_pending_diagnostic_updates: false,
4804                    progress_tokens: Default::default(),
4805                },
4806            );
4807            cx.notify();
4808        });
4809        Ok(())
4810    }
4811
4812    async fn handle_update_language_server(
4813        this: ModelHandle<Self>,
4814        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
4815        _: Arc<Client>,
4816        mut cx: AsyncAppContext,
4817    ) -> Result<()> {
4818        let language_server_id = envelope.payload.language_server_id as usize;
4819        match envelope
4820            .payload
4821            .variant
4822            .ok_or_else(|| anyhow!("invalid variant"))?
4823        {
4824            proto::update_language_server::Variant::WorkStart(payload) => {
4825                this.update(&mut cx, |this, cx| {
4826                    this.on_lsp_work_start(
4827                        language_server_id,
4828                        payload.token,
4829                        LanguageServerProgress {
4830                            message: payload.message,
4831                            percentage: payload.percentage.map(|p| p as usize),
4832                            last_update_at: Instant::now(),
4833                        },
4834                        cx,
4835                    );
4836                })
4837            }
4838            proto::update_language_server::Variant::WorkProgress(payload) => {
4839                this.update(&mut cx, |this, cx| {
4840                    this.on_lsp_work_progress(
4841                        language_server_id,
4842                        payload.token,
4843                        LanguageServerProgress {
4844                            message: payload.message,
4845                            percentage: payload.percentage.map(|p| p as usize),
4846                            last_update_at: Instant::now(),
4847                        },
4848                        cx,
4849                    );
4850                })
4851            }
4852            proto::update_language_server::Variant::WorkEnd(payload) => {
4853                this.update(&mut cx, |this, cx| {
4854                    this.on_lsp_work_end(language_server_id, payload.token, cx);
4855                })
4856            }
4857            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
4858                this.update(&mut cx, |this, cx| {
4859                    this.disk_based_diagnostics_started(language_server_id, cx);
4860                })
4861            }
4862            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
4863                this.update(&mut cx, |this, cx| {
4864                    this.disk_based_diagnostics_finished(language_server_id, cx)
4865                });
4866            }
4867        }
4868
4869        Ok(())
4870    }
4871
4872    async fn handle_update_buffer(
4873        this: ModelHandle<Self>,
4874        envelope: TypedEnvelope<proto::UpdateBuffer>,
4875        _: Arc<Client>,
4876        mut cx: AsyncAppContext,
4877    ) -> Result<()> {
4878        this.update(&mut cx, |this, cx| {
4879            let payload = envelope.payload.clone();
4880            let buffer_id = payload.buffer_id;
4881            let ops = payload
4882                .operations
4883                .into_iter()
4884                .map(language::proto::deserialize_operation)
4885                .collect::<Result<Vec<_>, _>>()?;
4886            let is_remote = this.is_remote();
4887            match this.opened_buffers.entry(buffer_id) {
4888                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
4889                    OpenBuffer::Strong(buffer) => {
4890                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
4891                    }
4892                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
4893                    OpenBuffer::Weak(_) => {}
4894                },
4895                hash_map::Entry::Vacant(e) => {
4896                    assert!(
4897                        is_remote,
4898                        "received buffer update from {:?}",
4899                        envelope.original_sender_id
4900                    );
4901                    e.insert(OpenBuffer::Operations(ops));
4902                }
4903            }
4904            Ok(())
4905        })
4906    }
4907
4908    async fn handle_create_buffer_for_peer(
4909        this: ModelHandle<Self>,
4910        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4911        _: Arc<Client>,
4912        mut cx: AsyncAppContext,
4913    ) -> Result<()> {
4914        this.update(&mut cx, |this, cx| {
4915            match envelope
4916                .payload
4917                .variant
4918                .ok_or_else(|| anyhow!("missing variant"))?
4919            {
4920                proto::create_buffer_for_peer::Variant::State(mut state) => {
4921                    let mut buffer_file = None;
4922                    if let Some(file) = state.file.take() {
4923                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
4924                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
4925                            anyhow!("no worktree found for id {}", file.worktree_id)
4926                        })?;
4927                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
4928                            as Arc<dyn language::File>);
4929                    }
4930
4931                    let buffer_id = state.id;
4932                    let buffer = cx.add_model(|_| {
4933                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
4934                    });
4935                    this.incomplete_buffers.insert(buffer_id, buffer);
4936                }
4937                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
4938                    let buffer = this
4939                        .incomplete_buffers
4940                        .get(&chunk.buffer_id)
4941                        .ok_or_else(|| {
4942                            anyhow!(
4943                                "received chunk for buffer {} without initial state",
4944                                chunk.buffer_id
4945                            )
4946                        })?
4947                        .clone();
4948                    let operations = chunk
4949                        .operations
4950                        .into_iter()
4951                        .map(language::proto::deserialize_operation)
4952                        .collect::<Result<Vec<_>>>()?;
4953                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
4954
4955                    if chunk.is_last {
4956                        this.incomplete_buffers.remove(&chunk.buffer_id);
4957                        this.register_buffer(&buffer, cx)?;
4958                    }
4959                }
4960            }
4961
4962            Ok(())
4963        })
4964    }
4965
4966    async fn handle_update_diff_base(
4967        this: ModelHandle<Self>,
4968        envelope: TypedEnvelope<proto::UpdateDiffBase>,
4969        _: Arc<Client>,
4970        mut cx: AsyncAppContext,
4971    ) -> Result<()> {
4972        this.update(&mut cx, |this, cx| {
4973            let buffer_id = envelope.payload.buffer_id;
4974            let diff_base = envelope.payload.diff_base;
4975            let buffer = this
4976                .opened_buffers
4977                .get_mut(&buffer_id)
4978                .and_then(|b| b.upgrade(cx))
4979                .ok_or_else(|| anyhow!("No such buffer {}", buffer_id))?;
4980
4981            buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
4982
4983            Ok(())
4984        })
4985    }
4986
4987    async fn handle_update_buffer_file(
4988        this: ModelHandle<Self>,
4989        envelope: TypedEnvelope<proto::UpdateBufferFile>,
4990        _: Arc<Client>,
4991        mut cx: AsyncAppContext,
4992    ) -> Result<()> {
4993        this.update(&mut cx, |this, cx| {
4994            let payload = envelope.payload.clone();
4995            let buffer_id = payload.buffer_id;
4996            let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
4997            let worktree = this
4998                .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
4999                .ok_or_else(|| anyhow!("no such worktree"))?;
5000            let file = File::from_proto(file, worktree, cx)?;
5001            let buffer = this
5002                .opened_buffers
5003                .get_mut(&buffer_id)
5004                .and_then(|b| b.upgrade(cx))
5005                .ok_or_else(|| anyhow!("no such buffer"))?;
5006            buffer.update(cx, |buffer, cx| {
5007                buffer.file_updated(Arc::new(file), cx).detach();
5008            });
5009            this.assign_language_to_buffer(&buffer, cx);
5010            Ok(())
5011        })
5012    }
5013
5014    async fn handle_save_buffer(
5015        this: ModelHandle<Self>,
5016        envelope: TypedEnvelope<proto::SaveBuffer>,
5017        _: Arc<Client>,
5018        mut cx: AsyncAppContext,
5019    ) -> Result<proto::BufferSaved> {
5020        let buffer_id = envelope.payload.buffer_id;
5021        let requested_version = deserialize_version(envelope.payload.version);
5022
5023        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5024            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5025            let buffer = this
5026                .opened_buffers
5027                .get(&buffer_id)
5028                .and_then(|buffer| buffer.upgrade(cx))
5029                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5030            Ok::<_, anyhow::Error>((project_id, buffer))
5031        })?;
5032        buffer
5033            .update(&mut cx, |buffer, _| {
5034                buffer.wait_for_version(requested_version)
5035            })
5036            .await;
5037
5038        let (saved_version, fingerprint, mtime) =
5039            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
5040        Ok(proto::BufferSaved {
5041            project_id,
5042            buffer_id,
5043            version: serialize_version(&saved_version),
5044            mtime: Some(mtime.into()),
5045            fingerprint,
5046        })
5047    }
5048
5049    async fn handle_reload_buffers(
5050        this: ModelHandle<Self>,
5051        envelope: TypedEnvelope<proto::ReloadBuffers>,
5052        _: Arc<Client>,
5053        mut cx: AsyncAppContext,
5054    ) -> Result<proto::ReloadBuffersResponse> {
5055        let sender_id = envelope.original_sender_id()?;
5056        let reload = this.update(&mut cx, |this, cx| {
5057            let mut buffers = HashSet::default();
5058            for buffer_id in &envelope.payload.buffer_ids {
5059                buffers.insert(
5060                    this.opened_buffers
5061                        .get(buffer_id)
5062                        .and_then(|buffer| buffer.upgrade(cx))
5063                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5064                );
5065            }
5066            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5067        })?;
5068
5069        let project_transaction = reload.await?;
5070        let project_transaction = this.update(&mut cx, |this, cx| {
5071            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5072        });
5073        Ok(proto::ReloadBuffersResponse {
5074            transaction: Some(project_transaction),
5075        })
5076    }
5077
5078    async fn handle_format_buffers(
5079        this: ModelHandle<Self>,
5080        envelope: TypedEnvelope<proto::FormatBuffers>,
5081        _: Arc<Client>,
5082        mut cx: AsyncAppContext,
5083    ) -> Result<proto::FormatBuffersResponse> {
5084        let sender_id = envelope.original_sender_id()?;
5085        let format = this.update(&mut cx, |this, cx| {
5086            let mut buffers = HashSet::default();
5087            for buffer_id in &envelope.payload.buffer_ids {
5088                buffers.insert(
5089                    this.opened_buffers
5090                        .get(buffer_id)
5091                        .and_then(|buffer| buffer.upgrade(cx))
5092                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5093                );
5094            }
5095            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5096            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5097        })?;
5098
5099        let project_transaction = format.await?;
5100        let project_transaction = this.update(&mut cx, |this, cx| {
5101            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5102        });
5103        Ok(proto::FormatBuffersResponse {
5104            transaction: Some(project_transaction),
5105        })
5106    }
5107
5108    async fn handle_get_completions(
5109        this: ModelHandle<Self>,
5110        envelope: TypedEnvelope<proto::GetCompletions>,
5111        _: Arc<Client>,
5112        mut cx: AsyncAppContext,
5113    ) -> Result<proto::GetCompletionsResponse> {
5114        let position = envelope
5115            .payload
5116            .position
5117            .and_then(language::proto::deserialize_anchor)
5118            .ok_or_else(|| anyhow!("invalid position"))?;
5119        let version = deserialize_version(envelope.payload.version);
5120        let buffer = this.read_with(&cx, |this, cx| {
5121            this.opened_buffers
5122                .get(&envelope.payload.buffer_id)
5123                .and_then(|buffer| buffer.upgrade(cx))
5124                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5125        })?;
5126        buffer
5127            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5128            .await;
5129        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5130        let completions = this
5131            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5132            .await?;
5133
5134        Ok(proto::GetCompletionsResponse {
5135            completions: completions
5136                .iter()
5137                .map(language::proto::serialize_completion)
5138                .collect(),
5139            version: serialize_version(&version),
5140        })
5141    }
5142
5143    async fn handle_apply_additional_edits_for_completion(
5144        this: ModelHandle<Self>,
5145        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5146        _: Arc<Client>,
5147        mut cx: AsyncAppContext,
5148    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5149        let (buffer, completion) = this.update(&mut cx, |this, cx| {
5150            let buffer = this
5151                .opened_buffers
5152                .get(&envelope.payload.buffer_id)
5153                .and_then(|buffer| buffer.upgrade(cx))
5154                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5155            let language = buffer.read(cx).language();
5156            let completion = language::proto::deserialize_completion(
5157                envelope
5158                    .payload
5159                    .completion
5160                    .ok_or_else(|| anyhow!("invalid completion"))?,
5161                language.cloned(),
5162            );
5163            Ok::<_, anyhow::Error>((buffer, completion))
5164        })?;
5165
5166        let completion = completion.await?;
5167
5168        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5169            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5170        });
5171
5172        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5173            transaction: apply_additional_edits
5174                .await?
5175                .as_ref()
5176                .map(language::proto::serialize_transaction),
5177        })
5178    }
5179
5180    async fn handle_get_code_actions(
5181        this: ModelHandle<Self>,
5182        envelope: TypedEnvelope<proto::GetCodeActions>,
5183        _: Arc<Client>,
5184        mut cx: AsyncAppContext,
5185    ) -> Result<proto::GetCodeActionsResponse> {
5186        let start = envelope
5187            .payload
5188            .start
5189            .and_then(language::proto::deserialize_anchor)
5190            .ok_or_else(|| anyhow!("invalid start"))?;
5191        let end = envelope
5192            .payload
5193            .end
5194            .and_then(language::proto::deserialize_anchor)
5195            .ok_or_else(|| anyhow!("invalid end"))?;
5196        let buffer = this.update(&mut cx, |this, cx| {
5197            this.opened_buffers
5198                .get(&envelope.payload.buffer_id)
5199                .and_then(|buffer| buffer.upgrade(cx))
5200                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5201        })?;
5202        buffer
5203            .update(&mut cx, |buffer, _| {
5204                buffer.wait_for_version(deserialize_version(envelope.payload.version))
5205            })
5206            .await;
5207
5208        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5209        let code_actions = this.update(&mut cx, |this, cx| {
5210            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5211        })?;
5212
5213        Ok(proto::GetCodeActionsResponse {
5214            actions: code_actions
5215                .await?
5216                .iter()
5217                .map(language::proto::serialize_code_action)
5218                .collect(),
5219            version: serialize_version(&version),
5220        })
5221    }
5222
5223    async fn handle_apply_code_action(
5224        this: ModelHandle<Self>,
5225        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5226        _: Arc<Client>,
5227        mut cx: AsyncAppContext,
5228    ) -> Result<proto::ApplyCodeActionResponse> {
5229        let sender_id = envelope.original_sender_id()?;
5230        let action = language::proto::deserialize_code_action(
5231            envelope
5232                .payload
5233                .action
5234                .ok_or_else(|| anyhow!("invalid action"))?,
5235        )?;
5236        let apply_code_action = this.update(&mut cx, |this, cx| {
5237            let buffer = this
5238                .opened_buffers
5239                .get(&envelope.payload.buffer_id)
5240                .and_then(|buffer| buffer.upgrade(cx))
5241                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5242            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5243        })?;
5244
5245        let project_transaction = apply_code_action.await?;
5246        let project_transaction = this.update(&mut cx, |this, cx| {
5247            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5248        });
5249        Ok(proto::ApplyCodeActionResponse {
5250            transaction: Some(project_transaction),
5251        })
5252    }
5253
5254    async fn handle_lsp_command<T: LspCommand>(
5255        this: ModelHandle<Self>,
5256        envelope: TypedEnvelope<T::ProtoRequest>,
5257        _: Arc<Client>,
5258        mut cx: AsyncAppContext,
5259    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5260    where
5261        <T::LspRequest as lsp::request::Request>::Result: Send,
5262    {
5263        let sender_id = envelope.original_sender_id()?;
5264        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5265        let buffer_handle = this.read_with(&cx, |this, _| {
5266            this.opened_buffers
5267                .get(&buffer_id)
5268                .and_then(|buffer| buffer.upgrade(&cx))
5269                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5270        })?;
5271        let request = T::from_proto(
5272            envelope.payload,
5273            this.clone(),
5274            buffer_handle.clone(),
5275            cx.clone(),
5276        )
5277        .await?;
5278        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5279        let response = this
5280            .update(&mut cx, |this, cx| {
5281                this.request_lsp(buffer_handle, request, cx)
5282            })
5283            .await?;
5284        this.update(&mut cx, |this, cx| {
5285            Ok(T::response_to_proto(
5286                response,
5287                this,
5288                sender_id,
5289                &buffer_version,
5290                cx,
5291            ))
5292        })
5293    }
5294
5295    async fn handle_get_project_symbols(
5296        this: ModelHandle<Self>,
5297        envelope: TypedEnvelope<proto::GetProjectSymbols>,
5298        _: Arc<Client>,
5299        mut cx: AsyncAppContext,
5300    ) -> Result<proto::GetProjectSymbolsResponse> {
5301        let symbols = this
5302            .update(&mut cx, |this, cx| {
5303                this.symbols(&envelope.payload.query, cx)
5304            })
5305            .await?;
5306
5307        Ok(proto::GetProjectSymbolsResponse {
5308            symbols: symbols.iter().map(serialize_symbol).collect(),
5309        })
5310    }
5311
5312    async fn handle_search_project(
5313        this: ModelHandle<Self>,
5314        envelope: TypedEnvelope<proto::SearchProject>,
5315        _: Arc<Client>,
5316        mut cx: AsyncAppContext,
5317    ) -> Result<proto::SearchProjectResponse> {
5318        let peer_id = envelope.original_sender_id()?;
5319        let query = SearchQuery::from_proto(envelope.payload)?;
5320        let result = this
5321            .update(&mut cx, |this, cx| this.search(query, cx))
5322            .await?;
5323
5324        this.update(&mut cx, |this, cx| {
5325            let mut locations = Vec::new();
5326            for (buffer, ranges) in result {
5327                for range in ranges {
5328                    let start = serialize_anchor(&range.start);
5329                    let end = serialize_anchor(&range.end);
5330                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5331                    locations.push(proto::Location {
5332                        buffer_id,
5333                        start: Some(start),
5334                        end: Some(end),
5335                    });
5336                }
5337            }
5338            Ok(proto::SearchProjectResponse { locations })
5339        })
5340    }
5341
5342    async fn handle_open_buffer_for_symbol(
5343        this: ModelHandle<Self>,
5344        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5345        _: Arc<Client>,
5346        mut cx: AsyncAppContext,
5347    ) -> Result<proto::OpenBufferForSymbolResponse> {
5348        let peer_id = envelope.original_sender_id()?;
5349        let symbol = envelope
5350            .payload
5351            .symbol
5352            .ok_or_else(|| anyhow!("invalid symbol"))?;
5353        let symbol = this
5354            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5355            .await?;
5356        let symbol = this.read_with(&cx, |this, _| {
5357            let signature = this.symbol_signature(&symbol.path);
5358            if signature == symbol.signature {
5359                Ok(symbol)
5360            } else {
5361                Err(anyhow!("invalid symbol signature"))
5362            }
5363        })?;
5364        let buffer = this
5365            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5366            .await?;
5367
5368        Ok(proto::OpenBufferForSymbolResponse {
5369            buffer_id: this.update(&mut cx, |this, cx| {
5370                this.create_buffer_for_peer(&buffer, peer_id, cx)
5371            }),
5372        })
5373    }
5374
5375    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5376        let mut hasher = Sha256::new();
5377        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5378        hasher.update(project_path.path.to_string_lossy().as_bytes());
5379        hasher.update(self.nonce.to_be_bytes());
5380        hasher.finalize().as_slice().try_into().unwrap()
5381    }
5382
5383    async fn handle_open_buffer_by_id(
5384        this: ModelHandle<Self>,
5385        envelope: TypedEnvelope<proto::OpenBufferById>,
5386        _: Arc<Client>,
5387        mut cx: AsyncAppContext,
5388    ) -> Result<proto::OpenBufferResponse> {
5389        let peer_id = envelope.original_sender_id()?;
5390        let buffer = this
5391            .update(&mut cx, |this, cx| {
5392                this.open_buffer_by_id(envelope.payload.id, cx)
5393            })
5394            .await?;
5395        this.update(&mut cx, |this, cx| {
5396            Ok(proto::OpenBufferResponse {
5397                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5398            })
5399        })
5400    }
5401
5402    async fn handle_open_buffer_by_path(
5403        this: ModelHandle<Self>,
5404        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5405        _: Arc<Client>,
5406        mut cx: AsyncAppContext,
5407    ) -> Result<proto::OpenBufferResponse> {
5408        let peer_id = envelope.original_sender_id()?;
5409        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5410        let open_buffer = this.update(&mut cx, |this, cx| {
5411            this.open_buffer(
5412                ProjectPath {
5413                    worktree_id,
5414                    path: PathBuf::from(envelope.payload.path).into(),
5415                },
5416                cx,
5417            )
5418        });
5419
5420        let buffer = open_buffer.await?;
5421        this.update(&mut cx, |this, cx| {
5422            Ok(proto::OpenBufferResponse {
5423                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5424            })
5425        })
5426    }
5427
5428    fn serialize_project_transaction_for_peer(
5429        &mut self,
5430        project_transaction: ProjectTransaction,
5431        peer_id: PeerId,
5432        cx: &AppContext,
5433    ) -> proto::ProjectTransaction {
5434        let mut serialized_transaction = proto::ProjectTransaction {
5435            buffer_ids: Default::default(),
5436            transactions: Default::default(),
5437        };
5438        for (buffer, transaction) in project_transaction.0 {
5439            serialized_transaction
5440                .buffer_ids
5441                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5442            serialized_transaction
5443                .transactions
5444                .push(language::proto::serialize_transaction(&transaction));
5445        }
5446        serialized_transaction
5447    }
5448
5449    fn deserialize_project_transaction(
5450        &mut self,
5451        message: proto::ProjectTransaction,
5452        push_to_history: bool,
5453        cx: &mut ModelContext<Self>,
5454    ) -> Task<Result<ProjectTransaction>> {
5455        cx.spawn(|this, mut cx| async move {
5456            let mut project_transaction = ProjectTransaction::default();
5457            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5458            {
5459                let buffer = this
5460                    .update(&mut cx, |this, cx| this.wait_for_buffer(buffer_id, cx))
5461                    .await?;
5462                let transaction = language::proto::deserialize_transaction(transaction)?;
5463                project_transaction.0.insert(buffer, transaction);
5464            }
5465
5466            for (buffer, transaction) in &project_transaction.0 {
5467                buffer
5468                    .update(&mut cx, |buffer, _| {
5469                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5470                    })
5471                    .await;
5472
5473                if push_to_history {
5474                    buffer.update(&mut cx, |buffer, _| {
5475                        buffer.push_transaction(transaction.clone(), Instant::now());
5476                    });
5477                }
5478            }
5479
5480            Ok(project_transaction)
5481        })
5482    }
5483
5484    fn create_buffer_for_peer(
5485        &mut self,
5486        buffer: &ModelHandle<Buffer>,
5487        peer_id: PeerId,
5488        cx: &AppContext,
5489    ) -> u64 {
5490        let buffer_id = buffer.read(cx).remote_id();
5491        if let Some(project_id) = self.remote_id() {
5492            let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5493            if shared_buffers.insert(buffer_id) {
5494                let buffer = buffer.read(cx);
5495                let state = buffer.to_proto();
5496                let operations = buffer.serialize_ops(cx);
5497                let client = self.client.clone();
5498                cx.background()
5499                    .spawn(
5500                        async move {
5501                            let mut operations = operations.await;
5502
5503                            client.send(proto::CreateBufferForPeer {
5504                                project_id,
5505                                peer_id: peer_id.0,
5506                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
5507                            })?;
5508
5509                            loop {
5510                                #[cfg(any(test, feature = "test-support"))]
5511                                const CHUNK_SIZE: usize = 5;
5512
5513                                #[cfg(not(any(test, feature = "test-support")))]
5514                                const CHUNK_SIZE: usize = 100;
5515
5516                                let chunk = operations
5517                                    .drain(..cmp::min(CHUNK_SIZE, operations.len()))
5518                                    .collect();
5519                                let is_last = operations.is_empty();
5520                                client.send(proto::CreateBufferForPeer {
5521                                    project_id,
5522                                    peer_id: peer_id.0,
5523                                    variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
5524                                        proto::BufferChunk {
5525                                            buffer_id,
5526                                            operations: chunk,
5527                                            is_last,
5528                                        },
5529                                    )),
5530                                })?;
5531
5532                                if is_last {
5533                                    break;
5534                                }
5535                            }
5536
5537                            Ok(())
5538                        }
5539                        .log_err(),
5540                    )
5541                    .detach();
5542            }
5543        }
5544
5545        buffer_id
5546    }
5547
5548    fn wait_for_buffer(
5549        &self,
5550        id: u64,
5551        cx: &mut ModelContext<Self>,
5552    ) -> Task<Result<ModelHandle<Buffer>>> {
5553        let mut opened_buffer_rx = self.opened_buffer.1.clone();
5554        cx.spawn(|this, mut cx| async move {
5555            let buffer = loop {
5556                let buffer = this.read_with(&cx, |this, cx| {
5557                    this.opened_buffers
5558                        .get(&id)
5559                        .and_then(|buffer| buffer.upgrade(cx))
5560                });
5561                if let Some(buffer) = buffer {
5562                    break buffer;
5563                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5564                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
5565                }
5566
5567                opened_buffer_rx
5568                    .next()
5569                    .await
5570                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5571            };
5572            buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
5573            Ok(buffer)
5574        })
5575    }
5576
5577    fn deserialize_symbol(
5578        &self,
5579        serialized_symbol: proto::Symbol,
5580    ) -> impl Future<Output = Result<Symbol>> {
5581        let languages = self.languages.clone();
5582        async move {
5583            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5584            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5585            let start = serialized_symbol
5586                .start
5587                .ok_or_else(|| anyhow!("invalid start"))?;
5588            let end = serialized_symbol
5589                .end
5590                .ok_or_else(|| anyhow!("invalid end"))?;
5591            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5592            let path = ProjectPath {
5593                worktree_id,
5594                path: PathBuf::from(serialized_symbol.path).into(),
5595            };
5596            let language = languages.select_language(&path.path);
5597            Ok(Symbol {
5598                language_server_name: LanguageServerName(
5599                    serialized_symbol.language_server_name.into(),
5600                ),
5601                source_worktree_id,
5602                path,
5603                label: {
5604                    match language {
5605                        Some(language) => {
5606                            language
5607                                .label_for_symbol(&serialized_symbol.name, kind)
5608                                .await
5609                        }
5610                        None => None,
5611                    }
5612                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
5613                },
5614
5615                name: serialized_symbol.name,
5616                range: PointUtf16::new(start.row, start.column)
5617                    ..PointUtf16::new(end.row, end.column),
5618                kind,
5619                signature: serialized_symbol
5620                    .signature
5621                    .try_into()
5622                    .map_err(|_| anyhow!("invalid signature"))?,
5623            })
5624        }
5625    }
5626
5627    async fn handle_buffer_saved(
5628        this: ModelHandle<Self>,
5629        envelope: TypedEnvelope<proto::BufferSaved>,
5630        _: Arc<Client>,
5631        mut cx: AsyncAppContext,
5632    ) -> Result<()> {
5633        let version = deserialize_version(envelope.payload.version);
5634        let mtime = envelope
5635            .payload
5636            .mtime
5637            .ok_or_else(|| anyhow!("missing mtime"))?
5638            .into();
5639
5640        this.update(&mut cx, |this, cx| {
5641            let buffer = this
5642                .opened_buffers
5643                .get(&envelope.payload.buffer_id)
5644                .and_then(|buffer| buffer.upgrade(cx));
5645            if let Some(buffer) = buffer {
5646                buffer.update(cx, |buffer, cx| {
5647                    buffer.did_save(version, envelope.payload.fingerprint, mtime, None, cx);
5648                });
5649            }
5650            Ok(())
5651        })
5652    }
5653
5654    async fn handle_buffer_reloaded(
5655        this: ModelHandle<Self>,
5656        envelope: TypedEnvelope<proto::BufferReloaded>,
5657        _: Arc<Client>,
5658        mut cx: AsyncAppContext,
5659    ) -> Result<()> {
5660        let payload = envelope.payload;
5661        let version = deserialize_version(payload.version);
5662        let line_ending = deserialize_line_ending(
5663            proto::LineEnding::from_i32(payload.line_ending)
5664                .ok_or_else(|| anyhow!("missing line ending"))?,
5665        );
5666        let mtime = payload
5667            .mtime
5668            .ok_or_else(|| anyhow!("missing mtime"))?
5669            .into();
5670        this.update(&mut cx, |this, cx| {
5671            let buffer = this
5672                .opened_buffers
5673                .get(&payload.buffer_id)
5674                .and_then(|buffer| buffer.upgrade(cx));
5675            if let Some(buffer) = buffer {
5676                buffer.update(cx, |buffer, cx| {
5677                    buffer.did_reload(version, payload.fingerprint, line_ending, mtime, cx);
5678                });
5679            }
5680            Ok(())
5681        })
5682    }
5683
5684    #[allow(clippy::type_complexity)]
5685    fn edits_from_lsp(
5686        &mut self,
5687        buffer: &ModelHandle<Buffer>,
5688        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
5689        version: Option<i32>,
5690        cx: &mut ModelContext<Self>,
5691    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
5692        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
5693        cx.background().spawn(async move {
5694            let snapshot = snapshot?;
5695            let mut lsp_edits = lsp_edits
5696                .into_iter()
5697                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
5698                .collect::<Vec<_>>();
5699            lsp_edits.sort_by_key(|(range, _)| range.start);
5700
5701            let mut lsp_edits = lsp_edits.into_iter().peekable();
5702            let mut edits = Vec::new();
5703            while let Some((mut range, mut new_text)) = lsp_edits.next() {
5704                // Clip invalid ranges provided by the language server.
5705                range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
5706                range.end = snapshot.clip_point_utf16(range.end, Bias::Left);
5707
5708                // Combine any LSP edits that are adjacent.
5709                //
5710                // Also, combine LSP edits that are separated from each other by only
5711                // a newline. This is important because for some code actions,
5712                // Rust-analyzer rewrites the entire buffer via a series of edits that
5713                // are separated by unchanged newline characters.
5714                //
5715                // In order for the diffing logic below to work properly, any edits that
5716                // cancel each other out must be combined into one.
5717                while let Some((next_range, next_text)) = lsp_edits.peek() {
5718                    if next_range.start > range.end {
5719                        if next_range.start.row > range.end.row + 1
5720                            || next_range.start.column > 0
5721                            || snapshot.clip_point_utf16(
5722                                PointUtf16::new(range.end.row, u32::MAX),
5723                                Bias::Left,
5724                            ) > range.end
5725                        {
5726                            break;
5727                        }
5728                        new_text.push('\n');
5729                    }
5730                    range.end = next_range.end;
5731                    new_text.push_str(next_text);
5732                    lsp_edits.next();
5733                }
5734
5735                // For multiline edits, perform a diff of the old and new text so that
5736                // we can identify the changes more precisely, preserving the locations
5737                // of any anchors positioned in the unchanged regions.
5738                if range.end.row > range.start.row {
5739                    let mut offset = range.start.to_offset(&snapshot);
5740                    let old_text = snapshot.text_for_range(range).collect::<String>();
5741
5742                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
5743                    let mut moved_since_edit = true;
5744                    for change in diff.iter_all_changes() {
5745                        let tag = change.tag();
5746                        let value = change.value();
5747                        match tag {
5748                            ChangeTag::Equal => {
5749                                offset += value.len();
5750                                moved_since_edit = true;
5751                            }
5752                            ChangeTag::Delete => {
5753                                let start = snapshot.anchor_after(offset);
5754                                let end = snapshot.anchor_before(offset + value.len());
5755                                if moved_since_edit {
5756                                    edits.push((start..end, String::new()));
5757                                } else {
5758                                    edits.last_mut().unwrap().0.end = end;
5759                                }
5760                                offset += value.len();
5761                                moved_since_edit = false;
5762                            }
5763                            ChangeTag::Insert => {
5764                                if moved_since_edit {
5765                                    let anchor = snapshot.anchor_after(offset);
5766                                    edits.push((anchor..anchor, value.to_string()));
5767                                } else {
5768                                    edits.last_mut().unwrap().1.push_str(value);
5769                                }
5770                                moved_since_edit = false;
5771                            }
5772                        }
5773                    }
5774                } else if range.end == range.start {
5775                    let anchor = snapshot.anchor_after(range.start);
5776                    edits.push((anchor..anchor, new_text));
5777                } else {
5778                    let edit_start = snapshot.anchor_after(range.start);
5779                    let edit_end = snapshot.anchor_before(range.end);
5780                    edits.push((edit_start..edit_end, new_text));
5781                }
5782            }
5783
5784            Ok(edits)
5785        })
5786    }
5787
5788    fn buffer_snapshot_for_lsp_version(
5789        &mut self,
5790        buffer: &ModelHandle<Buffer>,
5791        version: Option<i32>,
5792        cx: &AppContext,
5793    ) -> Result<TextBufferSnapshot> {
5794        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
5795
5796        if let Some(version) = version {
5797            let buffer_id = buffer.read(cx).remote_id();
5798            let snapshots = self
5799                .buffer_snapshots
5800                .get_mut(&buffer_id)
5801                .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
5802            let mut found_snapshot = None;
5803            snapshots.retain(|(snapshot_version, snapshot)| {
5804                if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
5805                    false
5806                } else {
5807                    if *snapshot_version == version {
5808                        found_snapshot = Some(snapshot.clone());
5809                    }
5810                    true
5811                }
5812            });
5813
5814            found_snapshot.ok_or_else(|| {
5815                anyhow!(
5816                    "snapshot not found for buffer {} at version {}",
5817                    buffer_id,
5818                    version
5819                )
5820            })
5821        } else {
5822            Ok((buffer.read(cx)).text_snapshot())
5823        }
5824    }
5825
5826    fn language_server_for_buffer(
5827        &self,
5828        buffer: &Buffer,
5829        cx: &AppContext,
5830    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
5831        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
5832            let name = language.lsp_adapter()?.name.clone();
5833            let worktree_id = file.worktree_id(cx);
5834            let key = (worktree_id, name);
5835
5836            if let Some(server_id) = self.language_server_ids.get(&key) {
5837                if let Some(LanguageServerState::Running {
5838                    adapter, server, ..
5839                }) = self.language_servers.get(server_id)
5840                {
5841                    return Some((adapter, server));
5842                }
5843            }
5844        }
5845
5846        None
5847    }
5848}
5849
5850impl WorktreeHandle {
5851    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
5852        match self {
5853            WorktreeHandle::Strong(handle) => Some(handle.clone()),
5854            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
5855        }
5856    }
5857}
5858
5859impl OpenBuffer {
5860    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
5861        match self {
5862            OpenBuffer::Strong(handle) => Some(handle.clone()),
5863            OpenBuffer::Weak(handle) => handle.upgrade(cx),
5864            OpenBuffer::Operations(_) => None,
5865        }
5866    }
5867}
5868
5869pub struct PathMatchCandidateSet {
5870    pub snapshot: Snapshot,
5871    pub include_ignored: bool,
5872    pub include_root_name: bool,
5873}
5874
5875impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5876    type Candidates = PathMatchCandidateSetIter<'a>;
5877
5878    fn id(&self) -> usize {
5879        self.snapshot.id().to_usize()
5880    }
5881
5882    fn len(&self) -> usize {
5883        if self.include_ignored {
5884            self.snapshot.file_count()
5885        } else {
5886            self.snapshot.visible_file_count()
5887        }
5888    }
5889
5890    fn prefix(&self) -> Arc<str> {
5891        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5892            self.snapshot.root_name().into()
5893        } else if self.include_root_name {
5894            format!("{}/", self.snapshot.root_name()).into()
5895        } else {
5896            "".into()
5897        }
5898    }
5899
5900    fn candidates(&'a self, start: usize) -> Self::Candidates {
5901        PathMatchCandidateSetIter {
5902            traversal: self.snapshot.files(self.include_ignored, start),
5903        }
5904    }
5905}
5906
5907pub struct PathMatchCandidateSetIter<'a> {
5908    traversal: Traversal<'a>,
5909}
5910
5911impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5912    type Item = fuzzy::PathMatchCandidate<'a>;
5913
5914    fn next(&mut self) -> Option<Self::Item> {
5915        self.traversal.next().map(|entry| {
5916            if let EntryKind::File(char_bag) = entry.kind {
5917                fuzzy::PathMatchCandidate {
5918                    path: &entry.path,
5919                    char_bag,
5920                }
5921            } else {
5922                unreachable!()
5923            }
5924        })
5925    }
5926}
5927
5928impl Entity for Project {
5929    type Event = Event;
5930
5931    fn release(&mut self, _: &mut gpui::MutableAppContext) {
5932        match &self.client_state {
5933            Some(ProjectClientState::Local { remote_id, .. }) => {
5934                self.client
5935                    .send(proto::UnshareProject {
5936                        project_id: *remote_id,
5937                    })
5938                    .log_err();
5939            }
5940            Some(ProjectClientState::Remote { remote_id, .. }) => {
5941                self.client
5942                    .send(proto::LeaveProject {
5943                        project_id: *remote_id,
5944                    })
5945                    .log_err();
5946            }
5947            _ => {}
5948        }
5949    }
5950
5951    fn app_will_quit(
5952        &mut self,
5953        _: &mut MutableAppContext,
5954    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
5955        let shutdown_futures = self
5956            .language_servers
5957            .drain()
5958            .map(|(_, server_state)| async {
5959                match server_state {
5960                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
5961                    LanguageServerState::Starting(starting_server) => {
5962                        starting_server.await?.shutdown()?.await
5963                    }
5964                }
5965            })
5966            .collect::<Vec<_>>();
5967
5968        Some(
5969            async move {
5970                futures::future::join_all(shutdown_futures).await;
5971            }
5972            .boxed(),
5973        )
5974    }
5975}
5976
5977impl Collaborator {
5978    fn from_proto(message: proto::Collaborator) -> Self {
5979        Self {
5980            peer_id: PeerId(message.peer_id),
5981            replica_id: message.replica_id as ReplicaId,
5982        }
5983    }
5984}
5985
5986impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5987    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5988        Self {
5989            worktree_id,
5990            path: path.as_ref().into(),
5991        }
5992    }
5993}
5994
5995fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
5996    proto::Symbol {
5997        language_server_name: symbol.language_server_name.0.to_string(),
5998        source_worktree_id: symbol.source_worktree_id.to_proto(),
5999        worktree_id: symbol.path.worktree_id.to_proto(),
6000        path: symbol.path.path.to_string_lossy().to_string(),
6001        name: symbol.name.clone(),
6002        kind: unsafe { mem::transmute(symbol.kind) },
6003        start: Some(proto::Point {
6004            row: symbol.range.start.row,
6005            column: symbol.range.start.column,
6006        }),
6007        end: Some(proto::Point {
6008            row: symbol.range.end.row,
6009            column: symbol.range.end.column,
6010        }),
6011        signature: symbol.signature.to_vec(),
6012    }
6013}
6014
6015fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6016    let mut path_components = path.components();
6017    let mut base_components = base.components();
6018    let mut components: Vec<Component> = Vec::new();
6019    loop {
6020        match (path_components.next(), base_components.next()) {
6021            (None, None) => break,
6022            (Some(a), None) => {
6023                components.push(a);
6024                components.extend(path_components.by_ref());
6025                break;
6026            }
6027            (None, _) => components.push(Component::ParentDir),
6028            (Some(a), Some(b)) if components.is_empty() && a == b => (),
6029            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6030            (Some(a), Some(_)) => {
6031                components.push(Component::ParentDir);
6032                for _ in base_components {
6033                    components.push(Component::ParentDir);
6034                }
6035                components.push(a);
6036                components.extend(path_components.by_ref());
6037                break;
6038            }
6039        }
6040    }
6041    components.iter().map(|c| c.as_os_str()).collect()
6042}
6043
6044impl Item for Buffer {
6045    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6046        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6047    }
6048}