project.rs

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