project.rs

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