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