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