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