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