project.rs

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