project.rs

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