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
 993        for open_buffer in self.opened_buffers.values_mut() {
 994            match open_buffer {
 995                OpenBuffer::Strong(_) => {}
 996                OpenBuffer::Weak(buffer) => {
 997                    if let Some(buffer) = buffer.upgrade(cx) {
 998                        *open_buffer = OpenBuffer::Strong(buffer);
 999                    }
1000                }
1001                OpenBuffer::Operations(_) => unreachable!(),
1002            }
1003        }
1004
1005        for worktree_handle in self.worktrees.iter_mut() {
1006            match worktree_handle {
1007                WorktreeHandle::Strong(_) => {}
1008                WorktreeHandle::Weak(worktree) => {
1009                    if let Some(worktree) = worktree.upgrade(cx) {
1010                        *worktree_handle = WorktreeHandle::Strong(worktree);
1011                    }
1012                }
1013            }
1014        }
1015
1016        for (server_id, status) in &self.language_server_statuses {
1017            self.client
1018                .send(proto::StartLanguageServer {
1019                    project_id,
1020                    server: Some(proto::LanguageServer {
1021                        id: *server_id as u64,
1022                        name: status.name.clone(),
1023                    }),
1024                })
1025                .log_err();
1026        }
1027
1028        self.client_subscriptions.push(
1029            self.client
1030                .subscribe_to_entity(project_id)
1031                .set_model(&cx.handle(), &mut cx.to_async()),
1032        );
1033
1034        let (metadata_changed_tx, mut metadata_changed_rx) = mpsc::unbounded();
1035        self.client_state = Some(ProjectClientState::Local {
1036            remote_id: project_id,
1037            metadata_changed: metadata_changed_tx,
1038            _maintain_metadata: cx.spawn_weak(move |this, mut cx| async move {
1039                let mut txs = Vec::new();
1040                while let Some(tx) = metadata_changed_rx.next().await {
1041                    txs.push(tx);
1042                    while let Ok(Some(next_tx)) = metadata_changed_rx.try_next() {
1043                        txs.push(next_tx);
1044                    }
1045
1046                    let Some(this) = this.upgrade(&cx) else { break };
1047                    let worktrees =
1048                        this.read_with(&cx, |this, cx| this.worktrees(cx).collect::<Vec<_>>());
1049                    let update_project = this
1050                        .read_with(&cx, |this, cx| {
1051                            this.client.request(proto::UpdateProject {
1052                                project_id,
1053                                worktrees: this.worktree_metadata_protos(cx),
1054                            })
1055                        })
1056                        .await;
1057                    if update_project.is_ok() {
1058                        for worktree in worktrees {
1059                            worktree.update(&mut cx, |worktree, cx| {
1060                                let worktree = worktree.as_local_mut().unwrap();
1061                                worktree.share(project_id, cx).detach_and_log_err(cx)
1062                            });
1063                        }
1064                    }
1065
1066                    for tx in txs.drain(..) {
1067                        let _ = tx.send(());
1068                    }
1069                }
1070            }),
1071        });
1072
1073        let _ = self.metadata_changed(cx);
1074        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1075        cx.notify();
1076        Ok(())
1077    }
1078
1079    pub fn reshared(
1080        &mut self,
1081        message: proto::ResharedProject,
1082        cx: &mut ModelContext<Self>,
1083    ) -> Result<()> {
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.collaborators
4851                .insert(collaborator.peer_id, collaborator);
4852            cx.notify();
4853        });
4854
4855        Ok(())
4856    }
4857
4858    async fn handle_update_project_collaborator(
4859        this: ModelHandle<Self>,
4860        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4861        _: Arc<Client>,
4862        mut cx: AsyncAppContext,
4863    ) -> Result<()> {
4864        let old_peer_id = envelope
4865            .payload
4866            .old_peer_id
4867            .ok_or_else(|| anyhow!("missing old peer id"))?;
4868        let new_peer_id = envelope
4869            .payload
4870            .new_peer_id
4871            .ok_or_else(|| anyhow!("missing new peer id"))?;
4872        this.update(&mut cx, |this, cx| {
4873            let collaborator = this
4874                .collaborators
4875                .remove(&old_peer_id)
4876                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4877            let is_host = collaborator.replica_id == 0;
4878            this.collaborators.insert(new_peer_id, collaborator);
4879
4880            let buffers = this.shared_buffers.remove(&old_peer_id);
4881            log::info!(
4882                "peer {} became {}. moving buffers {:?}",
4883                old_peer_id,
4884                new_peer_id,
4885                &buffers
4886            );
4887            if let Some(buffers) = buffers {
4888                this.shared_buffers.insert(new_peer_id, buffers);
4889            }
4890
4891            if is_host {
4892                this.synchronize_remote_buffers(cx).detach_and_log_err(cx);
4893            }
4894
4895            cx.emit(Event::CollaboratorUpdated {
4896                old_peer_id,
4897                new_peer_id,
4898            });
4899            cx.notify();
4900            Ok(())
4901        })
4902    }
4903
4904    async fn handle_remove_collaborator(
4905        this: ModelHandle<Self>,
4906        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4907        _: Arc<Client>,
4908        mut cx: AsyncAppContext,
4909    ) -> Result<()> {
4910        this.update(&mut cx, |this, cx| {
4911            let peer_id = envelope
4912                .payload
4913                .peer_id
4914                .ok_or_else(|| anyhow!("invalid peer id"))?;
4915            let replica_id = this
4916                .collaborators
4917                .remove(&peer_id)
4918                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4919                .replica_id;
4920            for buffer in this.opened_buffers.values() {
4921                if let Some(buffer) = buffer.upgrade(cx) {
4922                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4923                }
4924            }
4925            this.shared_buffers.remove(&peer_id);
4926
4927            cx.emit(Event::CollaboratorLeft(peer_id));
4928            cx.notify();
4929            Ok(())
4930        })
4931    }
4932
4933    async fn handle_update_project(
4934        this: ModelHandle<Self>,
4935        envelope: TypedEnvelope<proto::UpdateProject>,
4936        _: Arc<Client>,
4937        mut cx: AsyncAppContext,
4938    ) -> Result<()> {
4939        this.update(&mut cx, |this, cx| {
4940            // Don't handle messages that were sent before the response to us joining the project
4941            if envelope.message_id > this.join_project_response_message_id {
4942                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4943            }
4944            Ok(())
4945        })
4946    }
4947
4948    async fn handle_update_worktree(
4949        this: ModelHandle<Self>,
4950        envelope: TypedEnvelope<proto::UpdateWorktree>,
4951        _: Arc<Client>,
4952        mut cx: AsyncAppContext,
4953    ) -> Result<()> {
4954        this.update(&mut cx, |this, cx| {
4955            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4956            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4957                worktree.update(cx, |worktree, _| {
4958                    let worktree = worktree.as_remote_mut().unwrap();
4959                    worktree.update_from_remote(envelope.payload);
4960                });
4961            }
4962            Ok(())
4963        })
4964    }
4965
4966    async fn handle_create_project_entry(
4967        this: ModelHandle<Self>,
4968        envelope: TypedEnvelope<proto::CreateProjectEntry>,
4969        _: Arc<Client>,
4970        mut cx: AsyncAppContext,
4971    ) -> Result<proto::ProjectEntryResponse> {
4972        let worktree = this.update(&mut cx, |this, cx| {
4973            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4974            this.worktree_for_id(worktree_id, cx)
4975                .ok_or_else(|| anyhow!("worktree not found"))
4976        })?;
4977        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4978        let entry = worktree
4979            .update(&mut cx, |worktree, cx| {
4980                let worktree = worktree.as_local_mut().unwrap();
4981                let path = PathBuf::from(envelope.payload.path);
4982                worktree.create_entry(path, envelope.payload.is_directory, cx)
4983            })
4984            .await?;
4985        Ok(proto::ProjectEntryResponse {
4986            entry: Some((&entry).into()),
4987            worktree_scan_id: worktree_scan_id as u64,
4988        })
4989    }
4990
4991    async fn handle_rename_project_entry(
4992        this: ModelHandle<Self>,
4993        envelope: TypedEnvelope<proto::RenameProjectEntry>,
4994        _: Arc<Client>,
4995        mut cx: AsyncAppContext,
4996    ) -> Result<proto::ProjectEntryResponse> {
4997        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4998        let worktree = this.read_with(&cx, |this, cx| {
4999            this.worktree_for_entry(entry_id, cx)
5000                .ok_or_else(|| anyhow!("worktree not found"))
5001        })?;
5002        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5003        let entry = worktree
5004            .update(&mut cx, |worktree, cx| {
5005                let new_path = PathBuf::from(envelope.payload.new_path);
5006                worktree
5007                    .as_local_mut()
5008                    .unwrap()
5009                    .rename_entry(entry_id, new_path, cx)
5010                    .ok_or_else(|| anyhow!("invalid entry"))
5011            })?
5012            .await?;
5013        Ok(proto::ProjectEntryResponse {
5014            entry: Some((&entry).into()),
5015            worktree_scan_id: worktree_scan_id as u64,
5016        })
5017    }
5018
5019    async fn handle_copy_project_entry(
5020        this: ModelHandle<Self>,
5021        envelope: TypedEnvelope<proto::CopyProjectEntry>,
5022        _: Arc<Client>,
5023        mut cx: AsyncAppContext,
5024    ) -> Result<proto::ProjectEntryResponse> {
5025        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5026        let worktree = this.read_with(&cx, |this, cx| {
5027            this.worktree_for_entry(entry_id, cx)
5028                .ok_or_else(|| anyhow!("worktree not found"))
5029        })?;
5030        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5031        let entry = worktree
5032            .update(&mut cx, |worktree, cx| {
5033                let new_path = PathBuf::from(envelope.payload.new_path);
5034                worktree
5035                    .as_local_mut()
5036                    .unwrap()
5037                    .copy_entry(entry_id, new_path, cx)
5038                    .ok_or_else(|| anyhow!("invalid entry"))
5039            })?
5040            .await?;
5041        Ok(proto::ProjectEntryResponse {
5042            entry: Some((&entry).into()),
5043            worktree_scan_id: worktree_scan_id as u64,
5044        })
5045    }
5046
5047    async fn handle_delete_project_entry(
5048        this: ModelHandle<Self>,
5049        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
5050        _: Arc<Client>,
5051        mut cx: AsyncAppContext,
5052    ) -> Result<proto::ProjectEntryResponse> {
5053        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5054        let worktree = this.read_with(&cx, |this, cx| {
5055            this.worktree_for_entry(entry_id, cx)
5056                .ok_or_else(|| anyhow!("worktree not found"))
5057        })?;
5058        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5059        worktree
5060            .update(&mut cx, |worktree, cx| {
5061                worktree
5062                    .as_local_mut()
5063                    .unwrap()
5064                    .delete_entry(entry_id, cx)
5065                    .ok_or_else(|| anyhow!("invalid entry"))
5066            })?
5067            .await?;
5068        Ok(proto::ProjectEntryResponse {
5069            entry: None,
5070            worktree_scan_id: worktree_scan_id as u64,
5071        })
5072    }
5073
5074    async fn handle_update_diagnostic_summary(
5075        this: ModelHandle<Self>,
5076        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
5077        _: Arc<Client>,
5078        mut cx: AsyncAppContext,
5079    ) -> Result<()> {
5080        this.update(&mut cx, |this, cx| {
5081            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5082            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5083                if let Some(summary) = envelope.payload.summary {
5084                    let project_path = ProjectPath {
5085                        worktree_id,
5086                        path: Path::new(&summary.path).into(),
5087                    };
5088                    worktree.update(cx, |worktree, _| {
5089                        worktree
5090                            .as_remote_mut()
5091                            .unwrap()
5092                            .update_diagnostic_summary(project_path.path.clone(), &summary);
5093                    });
5094                    cx.emit(Event::DiagnosticsUpdated {
5095                        language_server_id: summary.language_server_id as usize,
5096                        path: project_path,
5097                    });
5098                }
5099            }
5100            Ok(())
5101        })
5102    }
5103
5104    async fn handle_start_language_server(
5105        this: ModelHandle<Self>,
5106        envelope: TypedEnvelope<proto::StartLanguageServer>,
5107        _: Arc<Client>,
5108        mut cx: AsyncAppContext,
5109    ) -> Result<()> {
5110        let server = envelope
5111            .payload
5112            .server
5113            .ok_or_else(|| anyhow!("invalid server"))?;
5114        this.update(&mut cx, |this, cx| {
5115            this.language_server_statuses.insert(
5116                server.id as usize,
5117                LanguageServerStatus {
5118                    name: server.name,
5119                    pending_work: Default::default(),
5120                    has_pending_diagnostic_updates: false,
5121                    progress_tokens: Default::default(),
5122                },
5123            );
5124            cx.notify();
5125        });
5126        Ok(())
5127    }
5128
5129    async fn handle_update_language_server(
5130        this: ModelHandle<Self>,
5131        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5132        _: Arc<Client>,
5133        mut cx: AsyncAppContext,
5134    ) -> Result<()> {
5135        this.update(&mut cx, |this, cx| {
5136            let language_server_id = envelope.payload.language_server_id as usize;
5137
5138            match envelope
5139                .payload
5140                .variant
5141                .ok_or_else(|| anyhow!("invalid variant"))?
5142            {
5143                proto::update_language_server::Variant::WorkStart(payload) => {
5144                    this.on_lsp_work_start(
5145                        language_server_id,
5146                        payload.token,
5147                        LanguageServerProgress {
5148                            message: payload.message,
5149                            percentage: payload.percentage.map(|p| p as usize),
5150                            last_update_at: Instant::now(),
5151                        },
5152                        cx,
5153                    );
5154                }
5155
5156                proto::update_language_server::Variant::WorkProgress(payload) => {
5157                    this.on_lsp_work_progress(
5158                        language_server_id,
5159                        payload.token,
5160                        LanguageServerProgress {
5161                            message: payload.message,
5162                            percentage: payload.percentage.map(|p| p as usize),
5163                            last_update_at: Instant::now(),
5164                        },
5165                        cx,
5166                    );
5167                }
5168
5169                proto::update_language_server::Variant::WorkEnd(payload) => {
5170                    this.on_lsp_work_end(language_server_id, payload.token, cx);
5171                }
5172
5173                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5174                    this.disk_based_diagnostics_started(language_server_id, cx);
5175                }
5176
5177                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5178                    this.disk_based_diagnostics_finished(language_server_id, cx)
5179                }
5180            }
5181
5182            Ok(())
5183        })
5184    }
5185
5186    async fn handle_update_buffer(
5187        this: ModelHandle<Self>,
5188        envelope: TypedEnvelope<proto::UpdateBuffer>,
5189        _: Arc<Client>,
5190        mut cx: AsyncAppContext,
5191    ) -> Result<()> {
5192        this.update(&mut cx, |this, cx| {
5193            let payload = envelope.payload.clone();
5194            let buffer_id = payload.buffer_id;
5195            let ops = payload
5196                .operations
5197                .into_iter()
5198                .map(language::proto::deserialize_operation)
5199                .collect::<Result<Vec<_>, _>>()?;
5200            let is_remote = this.is_remote();
5201            match this.opened_buffers.entry(buffer_id) {
5202                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5203                    OpenBuffer::Strong(buffer) => {
5204                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5205                    }
5206                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5207                    OpenBuffer::Weak(_) => {}
5208                },
5209                hash_map::Entry::Vacant(e) => {
5210                    assert!(
5211                        is_remote,
5212                        "received buffer update from {:?}",
5213                        envelope.original_sender_id
5214                    );
5215                    e.insert(OpenBuffer::Operations(ops));
5216                }
5217            }
5218            Ok(())
5219        })
5220    }
5221
5222    async fn handle_create_buffer_for_peer(
5223        this: ModelHandle<Self>,
5224        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5225        _: Arc<Client>,
5226        mut cx: AsyncAppContext,
5227    ) -> Result<()> {
5228        this.update(&mut cx, |this, cx| {
5229            match envelope
5230                .payload
5231                .variant
5232                .ok_or_else(|| anyhow!("missing variant"))?
5233            {
5234                proto::create_buffer_for_peer::Variant::State(mut state) => {
5235                    let mut buffer_file = None;
5236                    if let Some(file) = state.file.take() {
5237                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
5238                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5239                            anyhow!("no worktree found for id {}", file.worktree_id)
5240                        })?;
5241                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5242                            as Arc<dyn language::File>);
5243                    }
5244
5245                    let buffer_id = state.id;
5246                    let buffer = cx.add_model(|_| {
5247                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5248                    });
5249                    this.incomplete_remote_buffers
5250                        .insert(buffer_id, Some(buffer));
5251                }
5252                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5253                    let buffer = this
5254                        .incomplete_remote_buffers
5255                        .get(&chunk.buffer_id)
5256                        .cloned()
5257                        .flatten()
5258                        .ok_or_else(|| {
5259                            anyhow!(
5260                                "received chunk for buffer {} without initial state",
5261                                chunk.buffer_id
5262                            )
5263                        })?;
5264                    let operations = chunk
5265                        .operations
5266                        .into_iter()
5267                        .map(language::proto::deserialize_operation)
5268                        .collect::<Result<Vec<_>>>()?;
5269                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5270
5271                    if chunk.is_last {
5272                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
5273                        this.register_buffer(&buffer, cx)?;
5274                    }
5275                }
5276            }
5277
5278            Ok(())
5279        })
5280    }
5281
5282    async fn handle_update_diff_base(
5283        this: ModelHandle<Self>,
5284        envelope: TypedEnvelope<proto::UpdateDiffBase>,
5285        _: Arc<Client>,
5286        mut cx: AsyncAppContext,
5287    ) -> Result<()> {
5288        this.update(&mut cx, |this, cx| {
5289            let buffer_id = envelope.payload.buffer_id;
5290            let diff_base = envelope.payload.diff_base;
5291            if let Some(buffer) = this
5292                .opened_buffers
5293                .get_mut(&buffer_id)
5294                .and_then(|b| b.upgrade(cx))
5295                .or_else(|| {
5296                    this.incomplete_remote_buffers
5297                        .get(&buffer_id)
5298                        .cloned()
5299                        .flatten()
5300                })
5301            {
5302                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
5303            }
5304            Ok(())
5305        })
5306    }
5307
5308    async fn handle_update_buffer_file(
5309        this: ModelHandle<Self>,
5310        envelope: TypedEnvelope<proto::UpdateBufferFile>,
5311        _: Arc<Client>,
5312        mut cx: AsyncAppContext,
5313    ) -> Result<()> {
5314        let buffer_id = envelope.payload.buffer_id;
5315        let is_incomplete = this.read_with(&cx, |this, _| {
5316            this.incomplete_remote_buffers.contains_key(&buffer_id)
5317        });
5318
5319        let buffer = if is_incomplete {
5320            Some(
5321                this.update(&mut cx, |this, cx| {
5322                    this.wait_for_remote_buffer(buffer_id, cx)
5323                })
5324                .await?,
5325            )
5326        } else {
5327            None
5328        };
5329
5330        this.update(&mut cx, |this, cx| {
5331            let payload = envelope.payload.clone();
5332            if let Some(buffer) = buffer.or_else(|| {
5333                this.opened_buffers
5334                    .get(&buffer_id)
5335                    .and_then(|b| b.upgrade(cx))
5336            }) {
5337                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5338                let worktree = this
5339                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5340                    .ok_or_else(|| anyhow!("no such worktree"))?;
5341                let file = File::from_proto(file, worktree, cx)?;
5342                buffer.update(cx, |buffer, cx| {
5343                    buffer.file_updated(Arc::new(file), cx).detach();
5344                });
5345                this.detect_language_for_buffer(&buffer, cx);
5346            }
5347            Ok(())
5348        })
5349    }
5350
5351    async fn handle_save_buffer(
5352        this: ModelHandle<Self>,
5353        envelope: TypedEnvelope<proto::SaveBuffer>,
5354        _: Arc<Client>,
5355        mut cx: AsyncAppContext,
5356    ) -> Result<proto::BufferSaved> {
5357        let buffer_id = envelope.payload.buffer_id;
5358        let requested_version = deserialize_version(envelope.payload.version);
5359
5360        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5361            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5362            let buffer = this
5363                .opened_buffers
5364                .get(&buffer_id)
5365                .and_then(|buffer| buffer.upgrade(cx))
5366                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5367            Ok::<_, anyhow::Error>((project_id, buffer))
5368        })?;
5369        buffer
5370            .update(&mut cx, |buffer, _| {
5371                buffer.wait_for_version(requested_version)
5372            })
5373            .await;
5374
5375        let (saved_version, fingerprint, mtime) = this
5376            .update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
5377            .await?;
5378        Ok(proto::BufferSaved {
5379            project_id,
5380            buffer_id,
5381            version: serialize_version(&saved_version),
5382            mtime: Some(mtime.into()),
5383            fingerprint: language::proto::serialize_fingerprint(fingerprint),
5384        })
5385    }
5386
5387    async fn handle_reload_buffers(
5388        this: ModelHandle<Self>,
5389        envelope: TypedEnvelope<proto::ReloadBuffers>,
5390        _: Arc<Client>,
5391        mut cx: AsyncAppContext,
5392    ) -> Result<proto::ReloadBuffersResponse> {
5393        let sender_id = envelope.original_sender_id()?;
5394        let reload = this.update(&mut cx, |this, cx| {
5395            let mut buffers = HashSet::default();
5396            for buffer_id in &envelope.payload.buffer_ids {
5397                buffers.insert(
5398                    this.opened_buffers
5399                        .get(buffer_id)
5400                        .and_then(|buffer| buffer.upgrade(cx))
5401                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5402                );
5403            }
5404            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5405        })?;
5406
5407        let project_transaction = reload.await?;
5408        let project_transaction = this.update(&mut cx, |this, cx| {
5409            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5410        });
5411        Ok(proto::ReloadBuffersResponse {
5412            transaction: Some(project_transaction),
5413        })
5414    }
5415
5416    async fn handle_synchronize_buffers(
5417        this: ModelHandle<Self>,
5418        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5419        _: Arc<Client>,
5420        mut cx: AsyncAppContext,
5421    ) -> Result<proto::SynchronizeBuffersResponse> {
5422        let project_id = envelope.payload.project_id;
5423        let mut response = proto::SynchronizeBuffersResponse {
5424            buffers: Default::default(),
5425        };
5426
5427        this.update(&mut cx, |this, cx| {
5428            let Some(guest_id) = envelope.original_sender_id else {
5429                log::error!("missing original_sender_id on SynchronizeBuffers request");
5430                return;
5431            };
5432
5433            this.shared_buffers.entry(guest_id).or_default().clear();
5434            for buffer in envelope.payload.buffers {
5435                let buffer_id = buffer.id;
5436                let remote_version = language::proto::deserialize_version(buffer.version);
5437                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5438                    this.shared_buffers
5439                        .entry(guest_id)
5440                        .or_default()
5441                        .insert(buffer_id);
5442
5443                    let buffer = buffer.read(cx);
5444                    response.buffers.push(proto::BufferVersion {
5445                        id: buffer_id,
5446                        version: language::proto::serialize_version(&buffer.version),
5447                    });
5448
5449                    let operations = buffer.serialize_ops(Some(remote_version), cx);
5450                    let client = this.client.clone();
5451                    if let Some(file) = buffer.file() {
5452                        client
5453                            .send(proto::UpdateBufferFile {
5454                                project_id,
5455                                buffer_id: buffer_id as u64,
5456                                file: Some(file.to_proto()),
5457                            })
5458                            .log_err();
5459                    }
5460
5461                    client
5462                        .send(proto::UpdateDiffBase {
5463                            project_id,
5464                            buffer_id: buffer_id as u64,
5465                            diff_base: buffer.diff_base().map(Into::into),
5466                        })
5467                        .log_err();
5468
5469                    client
5470                        .send(proto::BufferReloaded {
5471                            project_id,
5472                            buffer_id,
5473                            version: language::proto::serialize_version(buffer.saved_version()),
5474                            mtime: Some(buffer.saved_mtime().into()),
5475                            fingerprint: language::proto::serialize_fingerprint(
5476                                buffer.saved_version_fingerprint(),
5477                            ),
5478                            line_ending: language::proto::serialize_line_ending(
5479                                buffer.line_ending(),
5480                            ) as i32,
5481                        })
5482                        .log_err();
5483
5484                    cx.background()
5485                        .spawn(
5486                            async move {
5487                                let operations = operations.await;
5488                                for chunk in split_operations(operations) {
5489                                    client
5490                                        .request(proto::UpdateBuffer {
5491                                            project_id,
5492                                            buffer_id,
5493                                            operations: chunk,
5494                                        })
5495                                        .await?;
5496                                }
5497                                anyhow::Ok(())
5498                            }
5499                            .log_err(),
5500                        )
5501                        .detach();
5502                }
5503            }
5504        });
5505
5506        Ok(response)
5507    }
5508
5509    async fn handle_format_buffers(
5510        this: ModelHandle<Self>,
5511        envelope: TypedEnvelope<proto::FormatBuffers>,
5512        _: Arc<Client>,
5513        mut cx: AsyncAppContext,
5514    ) -> Result<proto::FormatBuffersResponse> {
5515        let sender_id = envelope.original_sender_id()?;
5516        let format = this.update(&mut cx, |this, cx| {
5517            let mut buffers = HashSet::default();
5518            for buffer_id in &envelope.payload.buffer_ids {
5519                buffers.insert(
5520                    this.opened_buffers
5521                        .get(buffer_id)
5522                        .and_then(|buffer| buffer.upgrade(cx))
5523                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5524                );
5525            }
5526            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5527            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5528        })?;
5529
5530        let project_transaction = format.await?;
5531        let project_transaction = this.update(&mut cx, |this, cx| {
5532            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5533        });
5534        Ok(proto::FormatBuffersResponse {
5535            transaction: Some(project_transaction),
5536        })
5537    }
5538
5539    async fn handle_get_completions(
5540        this: ModelHandle<Self>,
5541        envelope: TypedEnvelope<proto::GetCompletions>,
5542        _: Arc<Client>,
5543        mut cx: AsyncAppContext,
5544    ) -> Result<proto::GetCompletionsResponse> {
5545        let buffer = this.read_with(&cx, |this, cx| {
5546            this.opened_buffers
5547                .get(&envelope.payload.buffer_id)
5548                .and_then(|buffer| buffer.upgrade(cx))
5549                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5550        })?;
5551
5552        let position = envelope
5553            .payload
5554            .position
5555            .and_then(language::proto::deserialize_anchor)
5556            .map(|p| {
5557                buffer.read_with(&cx, |buffer, _| {
5558                    buffer.clip_point_utf16(Unclipped(p.to_point_utf16(buffer)), Bias::Left)
5559                })
5560            })
5561            .ok_or_else(|| anyhow!("invalid position"))?;
5562
5563        let version = deserialize_version(envelope.payload.version);
5564        buffer
5565            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5566            .await;
5567        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5568
5569        let completions = this
5570            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5571            .await?;
5572
5573        Ok(proto::GetCompletionsResponse {
5574            completions: completions
5575                .iter()
5576                .map(language::proto::serialize_completion)
5577                .collect(),
5578            version: serialize_version(&version),
5579        })
5580    }
5581
5582    async fn handle_apply_additional_edits_for_completion(
5583        this: ModelHandle<Self>,
5584        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5585        _: Arc<Client>,
5586        mut cx: AsyncAppContext,
5587    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5588        let (buffer, completion) = this.update(&mut cx, |this, cx| {
5589            let buffer = this
5590                .opened_buffers
5591                .get(&envelope.payload.buffer_id)
5592                .and_then(|buffer| buffer.upgrade(cx))
5593                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5594            let language = buffer.read(cx).language();
5595            let completion = language::proto::deserialize_completion(
5596                envelope
5597                    .payload
5598                    .completion
5599                    .ok_or_else(|| anyhow!("invalid completion"))?,
5600                language.cloned(),
5601            );
5602            Ok::<_, anyhow::Error>((buffer, completion))
5603        })?;
5604
5605        let completion = completion.await?;
5606
5607        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5608            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5609        });
5610
5611        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5612            transaction: apply_additional_edits
5613                .await?
5614                .as_ref()
5615                .map(language::proto::serialize_transaction),
5616        })
5617    }
5618
5619    async fn handle_get_code_actions(
5620        this: ModelHandle<Self>,
5621        envelope: TypedEnvelope<proto::GetCodeActions>,
5622        _: Arc<Client>,
5623        mut cx: AsyncAppContext,
5624    ) -> Result<proto::GetCodeActionsResponse> {
5625        let start = envelope
5626            .payload
5627            .start
5628            .and_then(language::proto::deserialize_anchor)
5629            .ok_or_else(|| anyhow!("invalid start"))?;
5630        let end = envelope
5631            .payload
5632            .end
5633            .and_then(language::proto::deserialize_anchor)
5634            .ok_or_else(|| anyhow!("invalid end"))?;
5635        let buffer = this.update(&mut cx, |this, cx| {
5636            this.opened_buffers
5637                .get(&envelope.payload.buffer_id)
5638                .and_then(|buffer| buffer.upgrade(cx))
5639                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5640        })?;
5641        buffer
5642            .update(&mut cx, |buffer, _| {
5643                buffer.wait_for_version(deserialize_version(envelope.payload.version))
5644            })
5645            .await;
5646
5647        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5648        let code_actions = this.update(&mut cx, |this, cx| {
5649            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5650        })?;
5651
5652        Ok(proto::GetCodeActionsResponse {
5653            actions: code_actions
5654                .await?
5655                .iter()
5656                .map(language::proto::serialize_code_action)
5657                .collect(),
5658            version: serialize_version(&version),
5659        })
5660    }
5661
5662    async fn handle_apply_code_action(
5663        this: ModelHandle<Self>,
5664        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5665        _: Arc<Client>,
5666        mut cx: AsyncAppContext,
5667    ) -> Result<proto::ApplyCodeActionResponse> {
5668        let sender_id = envelope.original_sender_id()?;
5669        let action = language::proto::deserialize_code_action(
5670            envelope
5671                .payload
5672                .action
5673                .ok_or_else(|| anyhow!("invalid action"))?,
5674        )?;
5675        let apply_code_action = this.update(&mut cx, |this, cx| {
5676            let buffer = this
5677                .opened_buffers
5678                .get(&envelope.payload.buffer_id)
5679                .and_then(|buffer| buffer.upgrade(cx))
5680                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5681            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5682        })?;
5683
5684        let project_transaction = apply_code_action.await?;
5685        let project_transaction = this.update(&mut cx, |this, cx| {
5686            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5687        });
5688        Ok(proto::ApplyCodeActionResponse {
5689            transaction: Some(project_transaction),
5690        })
5691    }
5692
5693    async fn handle_lsp_command<T: LspCommand>(
5694        this: ModelHandle<Self>,
5695        envelope: TypedEnvelope<T::ProtoRequest>,
5696        _: Arc<Client>,
5697        mut cx: AsyncAppContext,
5698    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5699    where
5700        <T::LspRequest as lsp::request::Request>::Result: Send,
5701    {
5702        let sender_id = envelope.original_sender_id()?;
5703        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5704        let buffer_handle = this.read_with(&cx, |this, _| {
5705            this.opened_buffers
5706                .get(&buffer_id)
5707                .and_then(|buffer| buffer.upgrade(&cx))
5708                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5709        })?;
5710        let request = T::from_proto(
5711            envelope.payload,
5712            this.clone(),
5713            buffer_handle.clone(),
5714            cx.clone(),
5715        )
5716        .await?;
5717        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5718        let response = this
5719            .update(&mut cx, |this, cx| {
5720                this.request_lsp(buffer_handle, request, cx)
5721            })
5722            .await?;
5723        this.update(&mut cx, |this, cx| {
5724            Ok(T::response_to_proto(
5725                response,
5726                this,
5727                sender_id,
5728                &buffer_version,
5729                cx,
5730            ))
5731        })
5732    }
5733
5734    async fn handle_get_project_symbols(
5735        this: ModelHandle<Self>,
5736        envelope: TypedEnvelope<proto::GetProjectSymbols>,
5737        _: Arc<Client>,
5738        mut cx: AsyncAppContext,
5739    ) -> Result<proto::GetProjectSymbolsResponse> {
5740        let symbols = this
5741            .update(&mut cx, |this, cx| {
5742                this.symbols(&envelope.payload.query, cx)
5743            })
5744            .await?;
5745
5746        Ok(proto::GetProjectSymbolsResponse {
5747            symbols: symbols.iter().map(serialize_symbol).collect(),
5748        })
5749    }
5750
5751    async fn handle_search_project(
5752        this: ModelHandle<Self>,
5753        envelope: TypedEnvelope<proto::SearchProject>,
5754        _: Arc<Client>,
5755        mut cx: AsyncAppContext,
5756    ) -> Result<proto::SearchProjectResponse> {
5757        let peer_id = envelope.original_sender_id()?;
5758        let query = SearchQuery::from_proto(envelope.payload)?;
5759        let result = this
5760            .update(&mut cx, |this, cx| this.search(query, cx))
5761            .await?;
5762
5763        this.update(&mut cx, |this, cx| {
5764            let mut locations = Vec::new();
5765            for (buffer, ranges) in result {
5766                for range in ranges {
5767                    let start = serialize_anchor(&range.start);
5768                    let end = serialize_anchor(&range.end);
5769                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5770                    locations.push(proto::Location {
5771                        buffer_id,
5772                        start: Some(start),
5773                        end: Some(end),
5774                    });
5775                }
5776            }
5777            Ok(proto::SearchProjectResponse { locations })
5778        })
5779    }
5780
5781    async fn handle_open_buffer_for_symbol(
5782        this: ModelHandle<Self>,
5783        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5784        _: Arc<Client>,
5785        mut cx: AsyncAppContext,
5786    ) -> Result<proto::OpenBufferForSymbolResponse> {
5787        let peer_id = envelope.original_sender_id()?;
5788        let symbol = envelope
5789            .payload
5790            .symbol
5791            .ok_or_else(|| anyhow!("invalid symbol"))?;
5792        let symbol = this
5793            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5794            .await?;
5795        let symbol = this.read_with(&cx, |this, _| {
5796            let signature = this.symbol_signature(&symbol.path);
5797            if signature == symbol.signature {
5798                Ok(symbol)
5799            } else {
5800                Err(anyhow!("invalid symbol signature"))
5801            }
5802        })?;
5803        let buffer = this
5804            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5805            .await?;
5806
5807        Ok(proto::OpenBufferForSymbolResponse {
5808            buffer_id: this.update(&mut cx, |this, cx| {
5809                this.create_buffer_for_peer(&buffer, peer_id, cx)
5810            }),
5811        })
5812    }
5813
5814    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5815        let mut hasher = Sha256::new();
5816        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5817        hasher.update(project_path.path.to_string_lossy().as_bytes());
5818        hasher.update(self.nonce.to_be_bytes());
5819        hasher.finalize().as_slice().try_into().unwrap()
5820    }
5821
5822    async fn handle_open_buffer_by_id(
5823        this: ModelHandle<Self>,
5824        envelope: TypedEnvelope<proto::OpenBufferById>,
5825        _: Arc<Client>,
5826        mut cx: AsyncAppContext,
5827    ) -> Result<proto::OpenBufferResponse> {
5828        let peer_id = envelope.original_sender_id()?;
5829        let buffer = this
5830            .update(&mut cx, |this, cx| {
5831                this.open_buffer_by_id(envelope.payload.id, cx)
5832            })
5833            .await?;
5834        this.update(&mut cx, |this, cx| {
5835            Ok(proto::OpenBufferResponse {
5836                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5837            })
5838        })
5839    }
5840
5841    async fn handle_open_buffer_by_path(
5842        this: ModelHandle<Self>,
5843        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5844        _: Arc<Client>,
5845        mut cx: AsyncAppContext,
5846    ) -> Result<proto::OpenBufferResponse> {
5847        let peer_id = envelope.original_sender_id()?;
5848        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5849        let open_buffer = this.update(&mut cx, |this, cx| {
5850            this.open_buffer(
5851                ProjectPath {
5852                    worktree_id,
5853                    path: PathBuf::from(envelope.payload.path).into(),
5854                },
5855                cx,
5856            )
5857        });
5858
5859        let buffer = open_buffer.await?;
5860        this.update(&mut cx, |this, cx| {
5861            Ok(proto::OpenBufferResponse {
5862                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5863            })
5864        })
5865    }
5866
5867    fn serialize_project_transaction_for_peer(
5868        &mut self,
5869        project_transaction: ProjectTransaction,
5870        peer_id: proto::PeerId,
5871        cx: &mut MutableAppContext,
5872    ) -> proto::ProjectTransaction {
5873        let mut serialized_transaction = proto::ProjectTransaction {
5874            buffer_ids: Default::default(),
5875            transactions: Default::default(),
5876        };
5877        for (buffer, transaction) in project_transaction.0 {
5878            serialized_transaction
5879                .buffer_ids
5880                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5881            serialized_transaction
5882                .transactions
5883                .push(language::proto::serialize_transaction(&transaction));
5884        }
5885        serialized_transaction
5886    }
5887
5888    fn deserialize_project_transaction(
5889        &mut self,
5890        message: proto::ProjectTransaction,
5891        push_to_history: bool,
5892        cx: &mut ModelContext<Self>,
5893    ) -> Task<Result<ProjectTransaction>> {
5894        cx.spawn(|this, mut cx| async move {
5895            let mut project_transaction = ProjectTransaction::default();
5896            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5897            {
5898                let buffer = this
5899                    .update(&mut cx, |this, cx| {
5900                        this.wait_for_remote_buffer(buffer_id, cx)
5901                    })
5902                    .await?;
5903                let transaction = language::proto::deserialize_transaction(transaction)?;
5904                project_transaction.0.insert(buffer, transaction);
5905            }
5906
5907            for (buffer, transaction) in &project_transaction.0 {
5908                buffer
5909                    .update(&mut cx, |buffer, _| {
5910                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5911                    })
5912                    .await;
5913
5914                if push_to_history {
5915                    buffer.update(&mut cx, |buffer, _| {
5916                        buffer.push_transaction(transaction.clone(), Instant::now());
5917                    });
5918                }
5919            }
5920
5921            Ok(project_transaction)
5922        })
5923    }
5924
5925    fn create_buffer_for_peer(
5926        &mut self,
5927        buffer: &ModelHandle<Buffer>,
5928        peer_id: proto::PeerId,
5929        cx: &mut MutableAppContext,
5930    ) -> u64 {
5931        let buffer_id = buffer.read(cx).remote_id();
5932        if let Some(project_id) = self.remote_id() {
5933            let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5934            if shared_buffers.insert(buffer_id) {
5935                let buffer = buffer.clone();
5936                let operations = buffer.read(cx).serialize_ops(None, cx);
5937                let client = self.client.clone();
5938                cx.spawn(move |cx| async move {
5939                    let operations = operations.await;
5940                    let state = buffer.read_with(&cx, |buffer, _| buffer.to_proto());
5941
5942                    client.send(proto::CreateBufferForPeer {
5943                        project_id,
5944                        peer_id: Some(peer_id),
5945                        variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
5946                    })?;
5947
5948                    cx.background()
5949                        .spawn(async move {
5950                            let mut chunks = split_operations(operations).peekable();
5951                            while let Some(chunk) = chunks.next() {
5952                                let is_last = chunks.peek().is_none();
5953                                client.send(proto::CreateBufferForPeer {
5954                                    project_id,
5955                                    peer_id: Some(peer_id),
5956                                    variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
5957                                        proto::BufferChunk {
5958                                            buffer_id,
5959                                            operations: chunk,
5960                                            is_last,
5961                                        },
5962                                    )),
5963                                })?;
5964                            }
5965                            anyhow::Ok(())
5966                        })
5967                        .await
5968                })
5969                .detach()
5970            }
5971        }
5972
5973        buffer_id
5974    }
5975
5976    fn wait_for_remote_buffer(
5977        &mut self,
5978        id: u64,
5979        cx: &mut ModelContext<Self>,
5980    ) -> Task<Result<ModelHandle<Buffer>>> {
5981        let mut opened_buffer_rx = self.opened_buffer.1.clone();
5982
5983        cx.spawn_weak(|this, mut cx| async move {
5984            let buffer = loop {
5985                let Some(this) = this.upgrade(&cx) else {
5986                    return Err(anyhow!("project dropped"));
5987                };
5988                let buffer = this.read_with(&cx, |this, cx| {
5989                    this.opened_buffers
5990                        .get(&id)
5991                        .and_then(|buffer| buffer.upgrade(cx))
5992                });
5993                if let Some(buffer) = buffer {
5994                    break buffer;
5995                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5996                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
5997                }
5998
5999                this.update(&mut cx, |this, _| {
6000                    this.incomplete_remote_buffers.entry(id).or_default();
6001                });
6002                drop(this);
6003                opened_buffer_rx
6004                    .next()
6005                    .await
6006                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
6007            };
6008            buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
6009            Ok(buffer)
6010        })
6011    }
6012
6013    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
6014        let project_id = match self.client_state.as_ref() {
6015            Some(ProjectClientState::Remote {
6016                sharing_has_stopped,
6017                remote_id,
6018                ..
6019            }) => {
6020                if *sharing_has_stopped {
6021                    return Task::ready(Err(anyhow!(
6022                        "can't synchronize remote buffers on a readonly project"
6023                    )));
6024                } else {
6025                    *remote_id
6026                }
6027            }
6028            Some(ProjectClientState::Local { .. }) | None => {
6029                return Task::ready(Err(anyhow!(
6030                    "can't synchronize remote buffers on a local project"
6031                )))
6032            }
6033        };
6034
6035        let client = self.client.clone();
6036        cx.spawn(|this, cx| async move {
6037            let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
6038                let buffers = this
6039                    .opened_buffers
6040                    .iter()
6041                    .filter_map(|(id, buffer)| {
6042                        let buffer = buffer.upgrade(cx)?;
6043                        Some(proto::BufferVersion {
6044                            id: *id,
6045                            version: language::proto::serialize_version(&buffer.read(cx).version),
6046                        })
6047                    })
6048                    .collect();
6049                let incomplete_buffer_ids = this
6050                    .incomplete_remote_buffers
6051                    .keys()
6052                    .copied()
6053                    .collect::<Vec<_>>();
6054
6055                (buffers, incomplete_buffer_ids)
6056            });
6057            let response = client
6058                .request(proto::SynchronizeBuffers {
6059                    project_id,
6060                    buffers,
6061                })
6062                .await?;
6063
6064            let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
6065                let client = client.clone();
6066                let buffer_id = buffer.id;
6067                let remote_version = language::proto::deserialize_version(buffer.version);
6068                this.read_with(&cx, |this, cx| {
6069                    if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6070                        let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
6071                        cx.background().spawn(async move {
6072                            let operations = operations.await;
6073                            for chunk in split_operations(operations) {
6074                                client
6075                                    .request(proto::UpdateBuffer {
6076                                        project_id,
6077                                        buffer_id,
6078                                        operations: chunk,
6079                                    })
6080                                    .await?;
6081                            }
6082                            anyhow::Ok(())
6083                        })
6084                    } else {
6085                        Task::ready(Ok(()))
6086                    }
6087                })
6088            });
6089
6090            // Any incomplete buffers have open requests waiting. Request that the host sends
6091            // creates these buffers for us again to unblock any waiting futures.
6092            for id in incomplete_buffer_ids {
6093                cx.background()
6094                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
6095                    .detach();
6096            }
6097
6098            futures::future::join_all(send_updates_for_buffers)
6099                .await
6100                .into_iter()
6101                .collect()
6102        })
6103    }
6104
6105    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
6106        self.worktrees(cx)
6107            .map(|worktree| {
6108                let worktree = worktree.read(cx);
6109                proto::WorktreeMetadata {
6110                    id: worktree.id().to_proto(),
6111                    root_name: worktree.root_name().into(),
6112                    visible: worktree.is_visible(),
6113                    abs_path: worktree.abs_path().to_string_lossy().into(),
6114                }
6115            })
6116            .collect()
6117    }
6118
6119    fn set_worktrees_from_proto(
6120        &mut self,
6121        worktrees: Vec<proto::WorktreeMetadata>,
6122        cx: &mut ModelContext<Project>,
6123    ) -> Result<()> {
6124        let replica_id = self.replica_id();
6125        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
6126
6127        let mut old_worktrees_by_id = self
6128            .worktrees
6129            .drain(..)
6130            .filter_map(|worktree| {
6131                let worktree = worktree.upgrade(cx)?;
6132                Some((worktree.read(cx).id(), worktree))
6133            })
6134            .collect::<HashMap<_, _>>();
6135
6136        for worktree in worktrees {
6137            if let Some(old_worktree) =
6138                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
6139            {
6140                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
6141            } else {
6142                let worktree =
6143                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
6144                let _ = self.add_worktree(&worktree, cx);
6145            }
6146        }
6147
6148        let _ = self.metadata_changed(cx);
6149        for (id, _) in old_worktrees_by_id {
6150            cx.emit(Event::WorktreeRemoved(id));
6151        }
6152
6153        Ok(())
6154    }
6155
6156    fn set_collaborators_from_proto(
6157        &mut self,
6158        messages: Vec<proto::Collaborator>,
6159        cx: &mut ModelContext<Self>,
6160    ) -> Result<()> {
6161        let mut collaborators = HashMap::default();
6162        for message in messages {
6163            let collaborator = Collaborator::from_proto(message)?;
6164            collaborators.insert(collaborator.peer_id, collaborator);
6165        }
6166        for old_peer_id in self.collaborators.keys() {
6167            if !collaborators.contains_key(old_peer_id) {
6168                cx.emit(Event::CollaboratorLeft(*old_peer_id));
6169            }
6170        }
6171        self.collaborators = collaborators;
6172        Ok(())
6173    }
6174
6175    fn deserialize_symbol(
6176        &self,
6177        serialized_symbol: proto::Symbol,
6178    ) -> impl Future<Output = Result<Symbol>> {
6179        let languages = self.languages.clone();
6180        async move {
6181            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
6182            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
6183            let start = serialized_symbol
6184                .start
6185                .ok_or_else(|| anyhow!("invalid start"))?;
6186            let end = serialized_symbol
6187                .end
6188                .ok_or_else(|| anyhow!("invalid end"))?;
6189            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
6190            let path = ProjectPath {
6191                worktree_id,
6192                path: PathBuf::from(serialized_symbol.path).into(),
6193            };
6194            let language = languages.language_for_path(&path.path).await.log_err();
6195            Ok(Symbol {
6196                language_server_name: LanguageServerName(
6197                    serialized_symbol.language_server_name.into(),
6198                ),
6199                source_worktree_id,
6200                path,
6201                label: {
6202                    match language {
6203                        Some(language) => {
6204                            language
6205                                .label_for_symbol(&serialized_symbol.name, kind)
6206                                .await
6207                        }
6208                        None => None,
6209                    }
6210                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
6211                },
6212
6213                name: serialized_symbol.name,
6214                range: Unclipped(PointUtf16::new(start.row, start.column))
6215                    ..Unclipped(PointUtf16::new(end.row, end.column)),
6216                kind,
6217                signature: serialized_symbol
6218                    .signature
6219                    .try_into()
6220                    .map_err(|_| anyhow!("invalid signature"))?,
6221            })
6222        }
6223    }
6224
6225    async fn handle_buffer_saved(
6226        this: ModelHandle<Self>,
6227        envelope: TypedEnvelope<proto::BufferSaved>,
6228        _: Arc<Client>,
6229        mut cx: AsyncAppContext,
6230    ) -> Result<()> {
6231        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
6232        let version = deserialize_version(envelope.payload.version);
6233        let mtime = envelope
6234            .payload
6235            .mtime
6236            .ok_or_else(|| anyhow!("missing mtime"))?
6237            .into();
6238
6239        this.update(&mut cx, |this, cx| {
6240            let buffer = this
6241                .opened_buffers
6242                .get(&envelope.payload.buffer_id)
6243                .and_then(|buffer| buffer.upgrade(cx))
6244                .or_else(|| {
6245                    this.incomplete_remote_buffers
6246                        .get(&envelope.payload.buffer_id)
6247                        .and_then(|b| b.clone())
6248                });
6249            if let Some(buffer) = buffer {
6250                buffer.update(cx, |buffer, cx| {
6251                    buffer.did_save(version, fingerprint, mtime, cx);
6252                });
6253            }
6254            Ok(())
6255        })
6256    }
6257
6258    async fn handle_buffer_reloaded(
6259        this: ModelHandle<Self>,
6260        envelope: TypedEnvelope<proto::BufferReloaded>,
6261        _: Arc<Client>,
6262        mut cx: AsyncAppContext,
6263    ) -> Result<()> {
6264        let payload = envelope.payload;
6265        let version = deserialize_version(payload.version);
6266        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
6267        let line_ending = deserialize_line_ending(
6268            proto::LineEnding::from_i32(payload.line_ending)
6269                .ok_or_else(|| anyhow!("missing line ending"))?,
6270        );
6271        let mtime = payload
6272            .mtime
6273            .ok_or_else(|| anyhow!("missing mtime"))?
6274            .into();
6275        this.update(&mut cx, |this, cx| {
6276            let buffer = this
6277                .opened_buffers
6278                .get(&payload.buffer_id)
6279                .and_then(|buffer| buffer.upgrade(cx));
6280            if let Some(buffer) = buffer {
6281                buffer.update(cx, |buffer, cx| {
6282                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
6283                });
6284            }
6285            Ok(())
6286        })
6287    }
6288
6289    #[allow(clippy::type_complexity)]
6290    fn edits_from_lsp(
6291        &mut self,
6292        buffer: &ModelHandle<Buffer>,
6293        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
6294        version: Option<i32>,
6295        cx: &mut ModelContext<Self>,
6296    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
6297        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
6298        cx.background().spawn(async move {
6299            let snapshot = snapshot?;
6300            let mut lsp_edits = lsp_edits
6301                .into_iter()
6302                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
6303                .collect::<Vec<_>>();
6304            lsp_edits.sort_by_key(|(range, _)| range.start);
6305
6306            let mut lsp_edits = lsp_edits.into_iter().peekable();
6307            let mut edits = Vec::new();
6308            while let Some((range, mut new_text)) = lsp_edits.next() {
6309                // Clip invalid ranges provided by the language server.
6310                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
6311                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
6312
6313                // Combine any LSP edits that are adjacent.
6314                //
6315                // Also, combine LSP edits that are separated from each other by only
6316                // a newline. This is important because for some code actions,
6317                // Rust-analyzer rewrites the entire buffer via a series of edits that
6318                // are separated by unchanged newline characters.
6319                //
6320                // In order for the diffing logic below to work properly, any edits that
6321                // cancel each other out must be combined into one.
6322                while let Some((next_range, next_text)) = lsp_edits.peek() {
6323                    if next_range.start.0 > range.end {
6324                        if next_range.start.0.row > range.end.row + 1
6325                            || next_range.start.0.column > 0
6326                            || snapshot.clip_point_utf16(
6327                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
6328                                Bias::Left,
6329                            ) > range.end
6330                        {
6331                            break;
6332                        }
6333                        new_text.push('\n');
6334                    }
6335                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
6336                    new_text.push_str(next_text);
6337                    lsp_edits.next();
6338                }
6339
6340                // For multiline edits, perform a diff of the old and new text so that
6341                // we can identify the changes more precisely, preserving the locations
6342                // of any anchors positioned in the unchanged regions.
6343                if range.end.row > range.start.row {
6344                    let mut offset = range.start.to_offset(&snapshot);
6345                    let old_text = snapshot.text_for_range(range).collect::<String>();
6346
6347                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
6348                    let mut moved_since_edit = true;
6349                    for change in diff.iter_all_changes() {
6350                        let tag = change.tag();
6351                        let value = change.value();
6352                        match tag {
6353                            ChangeTag::Equal => {
6354                                offset += value.len();
6355                                moved_since_edit = true;
6356                            }
6357                            ChangeTag::Delete => {
6358                                let start = snapshot.anchor_after(offset);
6359                                let end = snapshot.anchor_before(offset + value.len());
6360                                if moved_since_edit {
6361                                    edits.push((start..end, String::new()));
6362                                } else {
6363                                    edits.last_mut().unwrap().0.end = end;
6364                                }
6365                                offset += value.len();
6366                                moved_since_edit = false;
6367                            }
6368                            ChangeTag::Insert => {
6369                                if moved_since_edit {
6370                                    let anchor = snapshot.anchor_after(offset);
6371                                    edits.push((anchor..anchor, value.to_string()));
6372                                } else {
6373                                    edits.last_mut().unwrap().1.push_str(value);
6374                                }
6375                                moved_since_edit = false;
6376                            }
6377                        }
6378                    }
6379                } else if range.end == range.start {
6380                    let anchor = snapshot.anchor_after(range.start);
6381                    edits.push((anchor..anchor, new_text));
6382                } else {
6383                    let edit_start = snapshot.anchor_after(range.start);
6384                    let edit_end = snapshot.anchor_before(range.end);
6385                    edits.push((edit_start..edit_end, new_text));
6386                }
6387            }
6388
6389            Ok(edits)
6390        })
6391    }
6392
6393    fn buffer_snapshot_for_lsp_version(
6394        &mut self,
6395        buffer: &ModelHandle<Buffer>,
6396        version: Option<i32>,
6397        cx: &AppContext,
6398    ) -> Result<TextBufferSnapshot> {
6399        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
6400
6401        if let Some(version) = version {
6402            let buffer_id = buffer.read(cx).remote_id();
6403            let snapshots = self
6404                .buffer_snapshots
6405                .get_mut(&buffer_id)
6406                .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
6407            let found_snapshot = snapshots
6408                .binary_search_by_key(&version, |e| e.0)
6409                .map(|ix| snapshots[ix].1.clone())
6410                .map_err(|_| {
6411                    anyhow!(
6412                        "snapshot not found for buffer {} at version {}",
6413                        buffer_id,
6414                        version
6415                    )
6416                })?;
6417            snapshots.retain(|(snapshot_version, _)| {
6418                snapshot_version + OLD_VERSIONS_TO_RETAIN >= version
6419            });
6420            Ok(found_snapshot)
6421        } else {
6422            Ok((buffer.read(cx)).text_snapshot())
6423        }
6424    }
6425
6426    fn language_server_for_buffer(
6427        &self,
6428        buffer: &Buffer,
6429        cx: &AppContext,
6430    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6431        let server_id = self.language_server_id_for_buffer(buffer, cx)?;
6432        let server = self.language_servers.get(&server_id)?;
6433        if let LanguageServerState::Running {
6434            adapter, server, ..
6435        } = server
6436        {
6437            Some((adapter, server))
6438        } else {
6439            None
6440        }
6441    }
6442
6443    fn language_server_id_for_buffer(&self, buffer: &Buffer, cx: &AppContext) -> Option<usize> {
6444        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6445            let name = language.lsp_adapter()?.name.clone();
6446            let worktree_id = file.worktree_id(cx);
6447            let key = (worktree_id, name);
6448            self.language_server_ids.get(&key).copied()
6449        } else {
6450            None
6451        }
6452    }
6453}
6454
6455impl WorktreeHandle {
6456    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6457        match self {
6458            WorktreeHandle::Strong(handle) => Some(handle.clone()),
6459            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6460        }
6461    }
6462}
6463
6464impl OpenBuffer {
6465    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
6466        match self {
6467            OpenBuffer::Strong(handle) => Some(handle.clone()),
6468            OpenBuffer::Weak(handle) => handle.upgrade(cx),
6469            OpenBuffer::Operations(_) => None,
6470        }
6471    }
6472}
6473
6474pub struct PathMatchCandidateSet {
6475    pub snapshot: Snapshot,
6476    pub include_ignored: bool,
6477    pub include_root_name: bool,
6478}
6479
6480impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6481    type Candidates = PathMatchCandidateSetIter<'a>;
6482
6483    fn id(&self) -> usize {
6484        self.snapshot.id().to_usize()
6485    }
6486
6487    fn len(&self) -> usize {
6488        if self.include_ignored {
6489            self.snapshot.file_count()
6490        } else {
6491            self.snapshot.visible_file_count()
6492        }
6493    }
6494
6495    fn prefix(&self) -> Arc<str> {
6496        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6497            self.snapshot.root_name().into()
6498        } else if self.include_root_name {
6499            format!("{}/", self.snapshot.root_name()).into()
6500        } else {
6501            "".into()
6502        }
6503    }
6504
6505    fn candidates(&'a self, start: usize) -> Self::Candidates {
6506        PathMatchCandidateSetIter {
6507            traversal: self.snapshot.files(self.include_ignored, start),
6508        }
6509    }
6510}
6511
6512pub struct PathMatchCandidateSetIter<'a> {
6513    traversal: Traversal<'a>,
6514}
6515
6516impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6517    type Item = fuzzy::PathMatchCandidate<'a>;
6518
6519    fn next(&mut self) -> Option<Self::Item> {
6520        self.traversal.next().map(|entry| {
6521            if let EntryKind::File(char_bag) = entry.kind {
6522                fuzzy::PathMatchCandidate {
6523                    path: &entry.path,
6524                    char_bag,
6525                }
6526            } else {
6527                unreachable!()
6528            }
6529        })
6530    }
6531}
6532
6533impl Entity for Project {
6534    type Event = Event;
6535
6536    fn release(&mut self, _: &mut gpui::MutableAppContext) {
6537        match &self.client_state {
6538            Some(ProjectClientState::Local { remote_id, .. }) => {
6539                let _ = self.client.send(proto::UnshareProject {
6540                    project_id: *remote_id,
6541                });
6542            }
6543            Some(ProjectClientState::Remote { remote_id, .. }) => {
6544                let _ = self.client.send(proto::LeaveProject {
6545                    project_id: *remote_id,
6546                });
6547            }
6548            _ => {}
6549        }
6550    }
6551
6552    fn app_will_quit(
6553        &mut self,
6554        _: &mut MutableAppContext,
6555    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6556        let shutdown_futures = self
6557            .language_servers
6558            .drain()
6559            .map(|(_, server_state)| async {
6560                match server_state {
6561                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6562                    LanguageServerState::Starting(starting_server) => {
6563                        starting_server.await?.shutdown()?.await
6564                    }
6565                }
6566            })
6567            .collect::<Vec<_>>();
6568
6569        Some(
6570            async move {
6571                futures::future::join_all(shutdown_futures).await;
6572            }
6573            .boxed(),
6574        )
6575    }
6576}
6577
6578impl Collaborator {
6579    fn from_proto(message: proto::Collaborator) -> Result<Self> {
6580        Ok(Self {
6581            peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
6582            replica_id: message.replica_id as ReplicaId,
6583        })
6584    }
6585}
6586
6587impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6588    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6589        Self {
6590            worktree_id,
6591            path: path.as_ref().into(),
6592        }
6593    }
6594}
6595
6596fn split_operations(
6597    mut operations: Vec<proto::Operation>,
6598) -> impl Iterator<Item = Vec<proto::Operation>> {
6599    #[cfg(any(test, feature = "test-support"))]
6600    const CHUNK_SIZE: usize = 5;
6601
6602    #[cfg(not(any(test, feature = "test-support")))]
6603    const CHUNK_SIZE: usize = 100;
6604
6605    let mut done = false;
6606    std::iter::from_fn(move || {
6607        if done {
6608            return None;
6609        }
6610
6611        let operations = operations
6612            .drain(..cmp::min(CHUNK_SIZE, operations.len()))
6613            .collect::<Vec<_>>();
6614        if operations.is_empty() {
6615            done = true;
6616        }
6617        Some(operations)
6618    })
6619}
6620
6621fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6622    proto::Symbol {
6623        language_server_name: symbol.language_server_name.0.to_string(),
6624        source_worktree_id: symbol.source_worktree_id.to_proto(),
6625        worktree_id: symbol.path.worktree_id.to_proto(),
6626        path: symbol.path.path.to_string_lossy().to_string(),
6627        name: symbol.name.clone(),
6628        kind: unsafe { mem::transmute(symbol.kind) },
6629        start: Some(proto::PointUtf16 {
6630            row: symbol.range.start.0.row,
6631            column: symbol.range.start.0.column,
6632        }),
6633        end: Some(proto::PointUtf16 {
6634            row: symbol.range.end.0.row,
6635            column: symbol.range.end.0.column,
6636        }),
6637        signature: symbol.signature.to_vec(),
6638    }
6639}
6640
6641fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6642    let mut path_components = path.components();
6643    let mut base_components = base.components();
6644    let mut components: Vec<Component> = Vec::new();
6645    loop {
6646        match (path_components.next(), base_components.next()) {
6647            (None, None) => break,
6648            (Some(a), None) => {
6649                components.push(a);
6650                components.extend(path_components.by_ref());
6651                break;
6652            }
6653            (None, _) => components.push(Component::ParentDir),
6654            (Some(a), Some(b)) if components.is_empty() && a == b => (),
6655            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6656            (Some(a), Some(_)) => {
6657                components.push(Component::ParentDir);
6658                for _ in base_components {
6659                    components.push(Component::ParentDir);
6660                }
6661                components.push(a);
6662                components.extend(path_components.by_ref());
6663                break;
6664            }
6665        }
6666    }
6667    components.iter().map(|c| c.as_os_str()).collect()
6668}
6669
6670impl Item for Buffer {
6671    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6672        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6673    }
6674
6675    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
6676        File::from_dyn(self.file()).map(|file| ProjectPath {
6677            worktree_id: file.worktree_id(cx),
6678            path: file.path().clone(),
6679        })
6680    }
6681}