project.rs

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