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