project.rs

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