project.rs

    1pub mod debounced_delay;
    2pub mod lsp_command;
    3pub mod lsp_ext_command;
    4mod prettier_support;
    5pub mod project_settings;
    6pub mod search;
    7mod task_inventory;
    8pub mod terminals;
    9
   10#[cfg(test)]
   11mod project_tests;
   12pub mod search_history;
   13
   14use anyhow::{anyhow, bail, Context as _, Result};
   15use async_trait::async_trait;
   16use client::{
   17    proto, Client, Collaborator, PendingEntitySubscription, ProjectId, TypedEnvelope, UserStore,
   18};
   19use clock::ReplicaId;
   20use collections::{hash_map, BTreeMap, HashMap, HashSet, VecDeque};
   21use copilot::Copilot;
   22use debounced_delay::DebouncedDelay;
   23use fs::repository::GitRepository;
   24use futures::{
   25    channel::{
   26        mpsc::{self, UnboundedReceiver},
   27        oneshot,
   28    },
   29    future::{join_all, try_join_all, Shared},
   30    select,
   31    stream::FuturesUnordered,
   32    AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
   33};
   34use git::blame::Blame;
   35use globset::{Glob, GlobSet, GlobSetBuilder};
   36use gpui::{
   37    AnyModel, AppContext, AsyncAppContext, BackgroundExecutor, BorrowAppContext, Context, Entity,
   38    EventEmitter, Model, ModelContext, PromptLevel, Task, WeakModel,
   39};
   40use itertools::Itertools;
   41use language::{
   42    language_settings::{language_settings, FormatOnSave, Formatter, InlayHintKind},
   43    markdown, point_to_lsp, prepare_completion_documentation,
   44    proto::{
   45        deserialize_anchor, deserialize_line_ending, deserialize_version, serialize_anchor,
   46        serialize_version, split_operations,
   47    },
   48    range_from_lsp, Bias, Buffer, BufferSnapshot, CachedLspAdapter, Capability, CodeLabel,
   49    Diagnostic, DiagnosticEntry, DiagnosticSet, Diff, Documentation, Event as BufferEvent,
   50    File as _, Language, LanguageRegistry, LanguageServerName, LocalFile, LspAdapterDelegate,
   51    Operation, Patch, PendingLanguageServer, PointUtf16, TextBufferSnapshot, ToOffset,
   52    ToPointUtf16, Transaction, Unclipped,
   53};
   54use log::error;
   55use lsp::{
   56    DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
   57    DocumentHighlightKind, LanguageServer, LanguageServerBinary, LanguageServerId,
   58    MessageActionItem, OneOf, ServerCapabilities, ServerHealthStatus, ServerStatus,
   59};
   60use lsp_command::*;
   61use node_runtime::NodeRuntime;
   62use parking_lot::{Mutex, RwLock};
   63use postage::watch;
   64use prettier_support::{DefaultPrettier, PrettierInstance};
   65use project_settings::{LspSettings, ProjectSettings};
   66use rand::prelude::*;
   67use search_history::SearchHistory;
   68use worktree::LocalSnapshot;
   69
   70use rpc::{ErrorCode, ErrorExt as _};
   71use search::SearchQuery;
   72use serde::Serialize;
   73use settings::{watch_config_file, Settings, SettingsLocation, SettingsStore};
   74use sha2::{Digest, Sha256};
   75use similar::{ChangeTag, TextDiff};
   76use smol::channel::{Receiver, Sender};
   77use smol::lock::Semaphore;
   78use std::{
   79    cmp::{self, Ordering},
   80    convert::TryInto,
   81    env,
   82    ffi::OsStr,
   83    hash::Hash,
   84    io, iter, mem,
   85    num::NonZeroU32,
   86    ops::Range,
   87    path::{self, Component, Path, PathBuf},
   88    process::Stdio,
   89    str::{self, FromStr},
   90    sync::{
   91        atomic::{AtomicUsize, Ordering::SeqCst},
   92        Arc,
   93    },
   94    time::{Duration, Instant},
   95};
   96use task::static_source::{StaticSource, TrackedFile};
   97use terminals::Terminals;
   98use text::{Anchor, BufferId, RopeFingerprint};
   99use util::{
  100    debug_panic, defer,
  101    http::{HttpClient, Url},
  102    maybe, merge_json_value_into, parse_env_output,
  103    paths::{
  104        LOCAL_SETTINGS_RELATIVE_PATH, LOCAL_TASKS_RELATIVE_PATH, LOCAL_VSCODE_TASKS_RELATIVE_PATH,
  105    },
  106    post_inc, ResultExt, TryFutureExt as _,
  107};
  108use worktree::{Snapshot, Traversal};
  109
  110pub use fs::*;
  111pub use language::Location;
  112#[cfg(any(test, feature = "test-support"))]
  113pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
  114#[cfg(feature = "test-support")]
  115pub use task_inventory::test_inventory::*;
  116pub use task_inventory::{Inventory, TaskSourceKind};
  117pub use worktree::{
  118    DiagnosticSummary, Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId,
  119    RepositoryEntry, UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId,
  120    WorktreeSettings, FS_WATCH_LATENCY,
  121};
  122
  123const MAX_SERVER_REINSTALL_ATTEMPT_COUNT: u64 = 4;
  124const SERVER_REINSTALL_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  125const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
  126pub const SERVER_PROGRESS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
  127
  128const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
  129
  130pub trait Item {
  131    fn try_open(
  132        project: &Model<Project>,
  133        path: &ProjectPath,
  134        cx: &mut AppContext,
  135    ) -> Option<Task<Result<Model<Self>>>>
  136    where
  137        Self: Sized;
  138    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  139    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
  140}
  141
  142#[derive(Clone)]
  143pub enum OpenedBufferEvent {
  144    Disconnected,
  145    Ok(BufferId),
  146    Err(BufferId, Arc<anyhow::Error>),
  147}
  148
  149/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
  150/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
  151/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
  152///
  153/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
  154pub struct Project {
  155    worktrees: Vec<WorktreeHandle>,
  156    active_entry: Option<ProjectEntryId>,
  157    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
  158    pending_language_server_update: Option<BufferOrderedMessage>,
  159    flush_language_server_update: Option<Task<()>>,
  160
  161    languages: Arc<LanguageRegistry>,
  162    supplementary_language_servers:
  163        HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
  164    language_servers: HashMap<LanguageServerId, LanguageServerState>,
  165    language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
  166    language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
  167    last_formatting_failure: Option<String>,
  168    last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
  169    language_server_watched_paths: HashMap<LanguageServerId, HashMap<WorktreeId, GlobSet>>,
  170    client: Arc<client::Client>,
  171    next_entry_id: Arc<AtomicUsize>,
  172    join_project_response_message_id: u32,
  173    next_diagnostic_group_id: usize,
  174    user_store: Model<UserStore>,
  175    fs: Arc<dyn Fs>,
  176    client_state: ProjectClientState,
  177    collaborators: HashMap<proto::PeerId, Collaborator>,
  178    client_subscriptions: Vec<client::Subscription>,
  179    _subscriptions: Vec<gpui::Subscription>,
  180    next_buffer_id: BufferId,
  181    loading_buffers: HashMap<BufferId, Vec<oneshot::Sender<Result<Model<Buffer>, anyhow::Error>>>>,
  182    incomplete_remote_buffers: HashMap<BufferId, Model<Buffer>>,
  183    shared_buffers: HashMap<proto::PeerId, HashSet<BufferId>>,
  184    #[allow(clippy::type_complexity)]
  185    loading_buffers_by_path: HashMap<
  186        ProjectPath,
  187        postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
  188    >,
  189    #[allow(clippy::type_complexity)]
  190    loading_local_worktrees:
  191        HashMap<Arc<Path>, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
  192    opened_buffers: HashMap<BufferId, OpenBuffer>,
  193    local_buffer_ids_by_path: HashMap<ProjectPath, BufferId>,
  194    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, BufferId>,
  195    buffer_snapshots: HashMap<BufferId, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
  196    buffers_being_formatted: HashSet<BufferId>,
  197    buffers_needing_diff: HashSet<WeakModel<Buffer>>,
  198    git_diff_debouncer: DebouncedDelay,
  199    nonce: u128,
  200    _maintain_buffer_languages: Task<()>,
  201    _maintain_workspace_config: Task<Result<()>>,
  202    terminals: Terminals,
  203    copilot_lsp_subscription: Option<gpui::Subscription>,
  204    copilot_log_subscription: Option<lsp::Subscription>,
  205    current_lsp_settings: HashMap<Arc<str>, LspSettings>,
  206    node: Option<Arc<dyn NodeRuntime>>,
  207    default_prettier: DefaultPrettier,
  208    prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
  209    prettier_instances: HashMap<PathBuf, PrettierInstance>,
  210    tasks: Model<Inventory>,
  211    hosted_project_id: Option<ProjectId>,
  212    search_history: SearchHistory,
  213}
  214
  215pub enum LanguageServerToQuery {
  216    Primary,
  217    Other(LanguageServerId),
  218}
  219
  220struct LspBufferSnapshot {
  221    version: i32,
  222    snapshot: TextBufferSnapshot,
  223}
  224
  225/// Message ordered with respect to buffer operations
  226#[derive(Debug)]
  227enum BufferOrderedMessage {
  228    Operation {
  229        buffer_id: BufferId,
  230        operation: proto::Operation,
  231    },
  232    LanguageServerUpdate {
  233        language_server_id: LanguageServerId,
  234        message: proto::update_language_server::Variant,
  235    },
  236    Resync,
  237}
  238
  239enum LocalProjectUpdate {
  240    WorktreesChanged,
  241    CreateBufferForPeer {
  242        peer_id: proto::PeerId,
  243        buffer_id: BufferId,
  244    },
  245}
  246
  247enum OpenBuffer {
  248    Strong(Model<Buffer>),
  249    Weak(WeakModel<Buffer>),
  250    Operations(Vec<Operation>),
  251}
  252
  253#[derive(Clone)]
  254enum WorktreeHandle {
  255    Strong(Model<Worktree>),
  256    Weak(WeakModel<Worktree>),
  257}
  258
  259#[derive(Debug)]
  260enum ProjectClientState {
  261    Local,
  262    Shared {
  263        remote_id: u64,
  264        updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
  265        _send_updates: Task<Result<()>>,
  266    },
  267    Remote {
  268        sharing_has_stopped: bool,
  269        capability: Capability,
  270        remote_id: u64,
  271        replica_id: ReplicaId,
  272    },
  273}
  274
  275/// A prompt requested by LSP server.
  276#[derive(Clone, Debug)]
  277pub struct LanguageServerPromptRequest {
  278    pub level: PromptLevel,
  279    pub message: String,
  280    pub actions: Vec<MessageActionItem>,
  281    pub lsp_name: String,
  282    response_channel: Sender<MessageActionItem>,
  283}
  284
  285impl LanguageServerPromptRequest {
  286    pub async fn respond(self, index: usize) -> Option<()> {
  287        if let Some(response) = self.actions.into_iter().nth(index) {
  288            self.response_channel.send(response).await.ok()
  289        } else {
  290            None
  291        }
  292    }
  293}
  294impl PartialEq for LanguageServerPromptRequest {
  295    fn eq(&self, other: &Self) -> bool {
  296        self.message == other.message && self.actions == other.actions
  297    }
  298}
  299
  300#[derive(Clone, Debug, PartialEq)]
  301pub enum Event {
  302    LanguageServerAdded(LanguageServerId),
  303    LanguageServerRemoved(LanguageServerId),
  304    LanguageServerLog(LanguageServerId, String),
  305    Notification(String),
  306    LanguageServerPrompt(LanguageServerPromptRequest),
  307    LanguageNotFound(Model<Buffer>),
  308    ActiveEntryChanged(Option<ProjectEntryId>),
  309    ActivateProjectPanel,
  310    WorktreeAdded,
  311    WorktreeRemoved(WorktreeId),
  312    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
  313    WorktreeUpdatedGitRepositories,
  314    DiskBasedDiagnosticsStarted {
  315        language_server_id: LanguageServerId,
  316    },
  317    DiskBasedDiagnosticsFinished {
  318        language_server_id: LanguageServerId,
  319    },
  320    DiagnosticsUpdated {
  321        path: ProjectPath,
  322        language_server_id: LanguageServerId,
  323    },
  324    RemoteIdChanged(Option<u64>),
  325    DisconnectedFromHost,
  326    Closed,
  327    DeletedEntry(ProjectEntryId),
  328    CollaboratorUpdated {
  329        old_peer_id: proto::PeerId,
  330        new_peer_id: proto::PeerId,
  331    },
  332    CollaboratorJoined(proto::PeerId),
  333    CollaboratorLeft(proto::PeerId),
  334    RefreshInlayHints,
  335    RevealInProjectPanel(ProjectEntryId),
  336}
  337
  338pub enum LanguageServerState {
  339    Starting(Task<Option<Arc<LanguageServer>>>),
  340
  341    Running {
  342        language: Arc<Language>,
  343        adapter: Arc<CachedLspAdapter>,
  344        server: Arc<LanguageServer>,
  345        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
  346    },
  347}
  348
  349#[derive(Serialize)]
  350pub struct LanguageServerStatus {
  351    pub name: String,
  352    pub pending_work: BTreeMap<String, LanguageServerProgress>,
  353    pub has_pending_diagnostic_updates: bool,
  354    progress_tokens: HashSet<String>,
  355}
  356
  357#[derive(Clone, Debug, Serialize)]
  358pub struct LanguageServerProgress {
  359    pub message: Option<String>,
  360    pub percentage: Option<usize>,
  361    #[serde(skip_serializing)]
  362    pub last_update_at: Instant,
  363}
  364
  365#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
  366pub struct ProjectPath {
  367    pub worktree_id: WorktreeId,
  368    pub path: Arc<Path>,
  369}
  370
  371#[derive(Debug, Clone, PartialEq, Eq)]
  372pub struct InlayHint {
  373    pub position: language::Anchor,
  374    pub label: InlayHintLabel,
  375    pub kind: Option<InlayHintKind>,
  376    pub padding_left: bool,
  377    pub padding_right: bool,
  378    pub tooltip: Option<InlayHintTooltip>,
  379    pub resolve_state: ResolveState,
  380}
  381
  382/// A completion provided by a language server
  383#[derive(Clone, Debug)]
  384pub struct Completion {
  385    /// The range of the buffer that will be replaced.
  386    pub old_range: Range<Anchor>,
  387    /// The new text that will be inserted.
  388    pub new_text: String,
  389    /// A label for this completion that is shown in the menu.
  390    pub label: CodeLabel,
  391    /// The id of the language server that produced this completion.
  392    pub server_id: LanguageServerId,
  393    /// The documentation for this completion.
  394    pub documentation: Option<Documentation>,
  395    /// The raw completion provided by the language server.
  396    pub lsp_completion: lsp::CompletionItem,
  397}
  398
  399/// A completion provided by a language server
  400#[derive(Clone, Debug)]
  401struct CoreCompletion {
  402    old_range: Range<Anchor>,
  403    new_text: String,
  404    server_id: LanguageServerId,
  405    lsp_completion: lsp::CompletionItem,
  406}
  407
  408/// A code action provided by a language server.
  409#[derive(Clone, Debug)]
  410pub struct CodeAction {
  411    /// The id of the language server that produced this code action.
  412    pub server_id: LanguageServerId,
  413    /// The range of the buffer where this code action is applicable.
  414    pub range: Range<Anchor>,
  415    /// The raw code action provided by the language server.
  416    pub lsp_action: lsp::CodeAction,
  417}
  418
  419#[derive(Debug, Clone, PartialEq, Eq)]
  420pub enum ResolveState {
  421    Resolved,
  422    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
  423    Resolving,
  424}
  425
  426impl InlayHint {
  427    pub fn text(&self) -> String {
  428        match &self.label {
  429            InlayHintLabel::String(s) => s.to_owned(),
  430            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
  431        }
  432    }
  433}
  434
  435#[derive(Debug, Clone, PartialEq, Eq)]
  436pub enum InlayHintLabel {
  437    String(String),
  438    LabelParts(Vec<InlayHintLabelPart>),
  439}
  440
  441#[derive(Debug, Clone, PartialEq, Eq)]
  442pub struct InlayHintLabelPart {
  443    pub value: String,
  444    pub tooltip: Option<InlayHintLabelPartTooltip>,
  445    pub location: Option<(LanguageServerId, lsp::Location)>,
  446}
  447
  448#[derive(Debug, Clone, PartialEq, Eq)]
  449pub enum InlayHintTooltip {
  450    String(String),
  451    MarkupContent(MarkupContent),
  452}
  453
  454#[derive(Debug, Clone, PartialEq, Eq)]
  455pub enum InlayHintLabelPartTooltip {
  456    String(String),
  457    MarkupContent(MarkupContent),
  458}
  459
  460#[derive(Debug, Clone, PartialEq, Eq)]
  461pub struct MarkupContent {
  462    pub kind: HoverBlockKind,
  463    pub value: String,
  464}
  465
  466#[derive(Debug, Clone)]
  467pub struct LocationLink {
  468    pub origin: Option<Location>,
  469    pub target: Location,
  470}
  471
  472#[derive(Debug)]
  473pub struct DocumentHighlight {
  474    pub range: Range<language::Anchor>,
  475    pub kind: DocumentHighlightKind,
  476}
  477
  478#[derive(Clone, Debug)]
  479pub struct Symbol {
  480    pub language_server_name: LanguageServerName,
  481    pub source_worktree_id: WorktreeId,
  482    pub path: ProjectPath,
  483    pub label: CodeLabel,
  484    pub name: String,
  485    pub kind: lsp::SymbolKind,
  486    pub range: Range<Unclipped<PointUtf16>>,
  487    pub signature: [u8; 32],
  488}
  489
  490#[derive(Clone, Debug)]
  491struct CoreSymbol {
  492    pub language_server_name: LanguageServerName,
  493    pub source_worktree_id: WorktreeId,
  494    pub path: ProjectPath,
  495    pub name: String,
  496    pub kind: lsp::SymbolKind,
  497    pub range: Range<Unclipped<PointUtf16>>,
  498    pub signature: [u8; 32],
  499}
  500
  501#[derive(Clone, Debug, PartialEq)]
  502pub struct HoverBlock {
  503    pub text: String,
  504    pub kind: HoverBlockKind,
  505}
  506
  507#[derive(Clone, Debug, PartialEq, Eq)]
  508pub enum HoverBlockKind {
  509    PlainText,
  510    Markdown,
  511    Code { language: String },
  512}
  513
  514#[derive(Debug, Clone)]
  515pub struct Hover {
  516    pub contents: Vec<HoverBlock>,
  517    pub range: Option<Range<language::Anchor>>,
  518    pub language: Option<Arc<Language>>,
  519}
  520
  521impl Hover {
  522    pub fn is_empty(&self) -> bool {
  523        self.contents.iter().all(|block| block.text.is_empty())
  524    }
  525}
  526
  527#[derive(Default)]
  528pub struct ProjectTransaction(pub HashMap<Model<Buffer>, language::Transaction>);
  529
  530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  531pub enum FormatTrigger {
  532    Save,
  533    Manual,
  534}
  535
  536// Currently, formatting operations are represented differently depending on
  537// whether they come from a language server or an external command.
  538enum FormatOperation {
  539    Lsp(Vec<(Range<Anchor>, String)>),
  540    External(Diff),
  541    Prettier(Diff),
  542}
  543
  544impl FormatTrigger {
  545    fn from_proto(value: i32) -> FormatTrigger {
  546        match value {
  547            0 => FormatTrigger::Save,
  548            1 => FormatTrigger::Manual,
  549            _ => FormatTrigger::Save,
  550        }
  551    }
  552}
  553
  554#[derive(Clone, Debug, PartialEq)]
  555enum SearchMatchCandidate {
  556    OpenBuffer {
  557        buffer: Model<Buffer>,
  558        // This might be an unnamed file without representation on filesystem
  559        path: Option<Arc<Path>>,
  560    },
  561    Path {
  562        worktree_id: WorktreeId,
  563        is_ignored: bool,
  564        path: Arc<Path>,
  565    },
  566}
  567
  568impl SearchMatchCandidate {
  569    fn path(&self) -> Option<Arc<Path>> {
  570        match self {
  571            SearchMatchCandidate::OpenBuffer { path, .. } => path.clone(),
  572            SearchMatchCandidate::Path { path, .. } => Some(path.clone()),
  573        }
  574    }
  575
  576    fn is_ignored(&self) -> bool {
  577        matches!(
  578            self,
  579            SearchMatchCandidate::Path {
  580                is_ignored: true,
  581                ..
  582            }
  583        )
  584    }
  585}
  586
  587pub enum SearchResult {
  588    Buffer {
  589        buffer: Model<Buffer>,
  590        ranges: Vec<Range<Anchor>>,
  591    },
  592    LimitReached,
  593}
  594
  595impl Project {
  596    pub fn init_settings(cx: &mut AppContext) {
  597        WorktreeSettings::register(cx);
  598        ProjectSettings::register(cx);
  599    }
  600
  601    pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
  602        Self::init_settings(cx);
  603
  604        client.add_model_message_handler(Self::handle_add_collaborator);
  605        client.add_model_message_handler(Self::handle_update_project_collaborator);
  606        client.add_model_message_handler(Self::handle_remove_collaborator);
  607        client.add_model_message_handler(Self::handle_buffer_reloaded);
  608        client.add_model_message_handler(Self::handle_buffer_saved);
  609        client.add_model_message_handler(Self::handle_start_language_server);
  610        client.add_model_message_handler(Self::handle_update_language_server);
  611        client.add_model_message_handler(Self::handle_update_project);
  612        client.add_model_message_handler(Self::handle_unshare_project);
  613        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
  614        client.add_model_message_handler(Self::handle_update_buffer_file);
  615        client.add_model_request_handler(Self::handle_update_buffer);
  616        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
  617        client.add_model_message_handler(Self::handle_update_worktree);
  618        client.add_model_message_handler(Self::handle_update_worktree_settings);
  619        client.add_model_request_handler(Self::handle_create_project_entry);
  620        client.add_model_request_handler(Self::handle_rename_project_entry);
  621        client.add_model_request_handler(Self::handle_copy_project_entry);
  622        client.add_model_request_handler(Self::handle_delete_project_entry);
  623        client.add_model_request_handler(Self::handle_expand_project_entry);
  624        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
  625        client.add_model_request_handler(Self::handle_resolve_completion_documentation);
  626        client.add_model_request_handler(Self::handle_apply_code_action);
  627        client.add_model_request_handler(Self::handle_on_type_formatting);
  628        client.add_model_request_handler(Self::handle_inlay_hints);
  629        client.add_model_request_handler(Self::handle_resolve_inlay_hint);
  630        client.add_model_request_handler(Self::handle_refresh_inlay_hints);
  631        client.add_model_request_handler(Self::handle_reload_buffers);
  632        client.add_model_request_handler(Self::handle_synchronize_buffers);
  633        client.add_model_request_handler(Self::handle_format_buffers);
  634        client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
  635        client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
  636        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
  637        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
  638        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
  639        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
  640        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
  641        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
  642        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
  643        client.add_model_request_handler(Self::handle_search_project);
  644        client.add_model_request_handler(Self::handle_get_project_symbols);
  645        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
  646        client.add_model_request_handler(Self::handle_open_buffer_by_id);
  647        client.add_model_request_handler(Self::handle_open_buffer_by_path);
  648        client.add_model_request_handler(Self::handle_save_buffer);
  649        client.add_model_message_handler(Self::handle_update_diff_base);
  650        client.add_model_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
  651        client.add_model_request_handler(Self::handle_blame_buffer);
  652        client.add_model_request_handler(Self::handle_multi_lsp_query);
  653    }
  654
  655    pub fn local(
  656        client: Arc<Client>,
  657        node: Arc<dyn NodeRuntime>,
  658        user_store: Model<UserStore>,
  659        languages: Arc<LanguageRegistry>,
  660        fs: Arc<dyn Fs>,
  661        cx: &mut AppContext,
  662    ) -> Model<Self> {
  663        cx.new_model(|cx: &mut ModelContext<Self>| {
  664            let (tx, rx) = mpsc::unbounded();
  665            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
  666                .detach();
  667            let copilot_lsp_subscription =
  668                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
  669            let tasks = Inventory::new(cx);
  670
  671            Self {
  672                worktrees: Vec::new(),
  673                buffer_ordered_messages_tx: tx,
  674                flush_language_server_update: None,
  675                pending_language_server_update: None,
  676                collaborators: Default::default(),
  677                next_buffer_id: BufferId::new(1).unwrap(),
  678                opened_buffers: Default::default(),
  679                shared_buffers: Default::default(),
  680                loading_buffers_by_path: Default::default(),
  681                loading_local_worktrees: Default::default(),
  682                local_buffer_ids_by_path: Default::default(),
  683                local_buffer_ids_by_entry_id: Default::default(),
  684                buffer_snapshots: Default::default(),
  685                join_project_response_message_id: 0,
  686                client_state: ProjectClientState::Local,
  687                loading_buffers: HashMap::default(),
  688                incomplete_remote_buffers: HashMap::default(),
  689                client_subscriptions: Vec::new(),
  690                _subscriptions: vec![
  691                    cx.observe_global::<SettingsStore>(Self::on_settings_changed),
  692                    cx.on_release(Self::release),
  693                    cx.on_app_quit(Self::shutdown_language_servers),
  694                ],
  695                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
  696                _maintain_workspace_config: Self::maintain_workspace_config(cx),
  697                active_entry: None,
  698                languages,
  699                client,
  700                user_store,
  701                fs,
  702                next_entry_id: Default::default(),
  703                next_diagnostic_group_id: Default::default(),
  704                supplementary_language_servers: HashMap::default(),
  705                language_servers: Default::default(),
  706                language_server_ids: HashMap::default(),
  707                language_server_statuses: Default::default(),
  708                last_formatting_failure: None,
  709                last_workspace_edits_by_language_server: Default::default(),
  710                language_server_watched_paths: HashMap::default(),
  711                buffers_being_formatted: Default::default(),
  712                buffers_needing_diff: Default::default(),
  713                git_diff_debouncer: DebouncedDelay::new(),
  714                nonce: StdRng::from_entropy().gen(),
  715                terminals: Terminals {
  716                    local_handles: Vec::new(),
  717                },
  718                copilot_lsp_subscription,
  719                copilot_log_subscription: None,
  720                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
  721                node: Some(node),
  722                default_prettier: DefaultPrettier::default(),
  723                prettiers_per_worktree: HashMap::default(),
  724                prettier_instances: HashMap::default(),
  725                tasks,
  726                hosted_project_id: None,
  727                search_history: Self::new_search_history(),
  728            }
  729        })
  730    }
  731
  732    pub async fn remote(
  733        remote_id: u64,
  734        client: Arc<Client>,
  735        user_store: Model<UserStore>,
  736        languages: Arc<LanguageRegistry>,
  737        fs: Arc<dyn Fs>,
  738        cx: AsyncAppContext,
  739    ) -> Result<Model<Self>> {
  740        client.authenticate_and_connect(true, &cx).await?;
  741
  742        let subscription = client.subscribe_to_entity(remote_id)?;
  743        let response = client
  744            .request_envelope(proto::JoinProject {
  745                project_id: remote_id,
  746            })
  747            .await?;
  748        Self::from_join_project_response(
  749            response,
  750            subscription,
  751            client,
  752            user_store,
  753            languages,
  754            fs,
  755            cx,
  756        )
  757        .await
  758    }
  759    async fn from_join_project_response(
  760        response: TypedEnvelope<proto::JoinProjectResponse>,
  761        subscription: PendingEntitySubscription<Project>,
  762        client: Arc<Client>,
  763        user_store: Model<UserStore>,
  764        languages: Arc<LanguageRegistry>,
  765        fs: Arc<dyn Fs>,
  766        mut cx: AsyncAppContext,
  767    ) -> Result<Model<Self>> {
  768        let remote_id = response.payload.project_id;
  769        let role = response.payload.role();
  770        let this = cx.new_model(|cx| {
  771            let replica_id = response.payload.replica_id as ReplicaId;
  772            let tasks = Inventory::new(cx);
  773            // BIG CAUTION NOTE: The order in which we initialize fields here matters and it should match what's done in Self::local.
  774            // Otherwise, you might run into issues where worktree id on remote is different than what's on local host.
  775            // That's because Worktree's identifier is entity id, which should probably be changed.
  776            let mut worktrees = Vec::new();
  777            for worktree in response.payload.worktrees {
  778                let worktree =
  779                    Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
  780                worktrees.push(worktree);
  781            }
  782
  783            let (tx, rx) = mpsc::unbounded();
  784            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
  785                .detach();
  786            let copilot_lsp_subscription =
  787                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
  788            let mut this = Self {
  789                worktrees: Vec::new(),
  790                buffer_ordered_messages_tx: tx,
  791                pending_language_server_update: None,
  792                flush_language_server_update: None,
  793                loading_buffers_by_path: Default::default(),
  794                next_buffer_id: BufferId::new(1).unwrap(),
  795                loading_buffers: Default::default(),
  796                shared_buffers: Default::default(),
  797                incomplete_remote_buffers: Default::default(),
  798                loading_local_worktrees: Default::default(),
  799                local_buffer_ids_by_path: Default::default(),
  800                local_buffer_ids_by_entry_id: Default::default(),
  801                active_entry: None,
  802                collaborators: Default::default(),
  803                join_project_response_message_id: response.message_id,
  804                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
  805                _maintain_workspace_config: Self::maintain_workspace_config(cx),
  806                languages,
  807                user_store: user_store.clone(),
  808                fs,
  809                next_entry_id: Default::default(),
  810                next_diagnostic_group_id: Default::default(),
  811                client_subscriptions: Default::default(),
  812                _subscriptions: vec![
  813                    cx.on_release(Self::release),
  814                    cx.on_app_quit(Self::shutdown_language_servers),
  815                ],
  816                client: client.clone(),
  817                client_state: ProjectClientState::Remote {
  818                    sharing_has_stopped: false,
  819                    capability: Capability::ReadWrite,
  820                    remote_id,
  821                    replica_id,
  822                },
  823                supplementary_language_servers: HashMap::default(),
  824                language_servers: Default::default(),
  825                language_server_ids: HashMap::default(),
  826                language_server_statuses: response
  827                    .payload
  828                    .language_servers
  829                    .into_iter()
  830                    .map(|server| {
  831                        (
  832                            LanguageServerId(server.id as usize),
  833                            LanguageServerStatus {
  834                                name: server.name,
  835                                pending_work: Default::default(),
  836                                has_pending_diagnostic_updates: false,
  837                                progress_tokens: Default::default(),
  838                            },
  839                        )
  840                    })
  841                    .collect(),
  842                last_formatting_failure: None,
  843                last_workspace_edits_by_language_server: Default::default(),
  844                language_server_watched_paths: HashMap::default(),
  845                opened_buffers: Default::default(),
  846                buffers_being_formatted: Default::default(),
  847                buffers_needing_diff: Default::default(),
  848                git_diff_debouncer: DebouncedDelay::new(),
  849                buffer_snapshots: Default::default(),
  850                nonce: StdRng::from_entropy().gen(),
  851                terminals: Terminals {
  852                    local_handles: Vec::new(),
  853                },
  854                copilot_lsp_subscription,
  855                copilot_log_subscription: None,
  856                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
  857                node: None,
  858                default_prettier: DefaultPrettier::default(),
  859                prettiers_per_worktree: HashMap::default(),
  860                prettier_instances: HashMap::default(),
  861                tasks,
  862                hosted_project_id: None,
  863                search_history: Self::new_search_history(),
  864            };
  865            this.set_role(role, cx);
  866            for worktree in worktrees {
  867                let _ = this.add_worktree(&worktree, cx);
  868            }
  869            this
  870        })?;
  871        let subscription = subscription.set_model(&this, &mut cx);
  872
  873        let user_ids = response
  874            .payload
  875            .collaborators
  876            .iter()
  877            .map(|peer| peer.user_id)
  878            .collect();
  879        user_store
  880            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
  881            .await?;
  882
  883        this.update(&mut cx, |this, cx| {
  884            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
  885            this.client_subscriptions.push(subscription);
  886            anyhow::Ok(())
  887        })??;
  888
  889        Ok(this)
  890    }
  891
  892    pub async fn hosted(
  893        remote_id: ProjectId,
  894        user_store: Model<UserStore>,
  895        client: Arc<Client>,
  896        languages: Arc<LanguageRegistry>,
  897        fs: Arc<dyn Fs>,
  898        cx: AsyncAppContext,
  899    ) -> Result<Model<Self>> {
  900        client.authenticate_and_connect(true, &cx).await?;
  901
  902        let subscription = client.subscribe_to_entity(remote_id.0)?;
  903        let response = client
  904            .request_envelope(proto::JoinHostedProject {
  905                project_id: remote_id.0,
  906            })
  907            .await?;
  908        Self::from_join_project_response(
  909            response,
  910            subscription,
  911            client,
  912            user_store,
  913            languages,
  914            fs,
  915            cx,
  916        )
  917        .await
  918    }
  919
  920    fn new_search_history() -> SearchHistory {
  921        SearchHistory::new(
  922            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
  923            search_history::QueryInsertionBehavior::AlwaysInsert,
  924        )
  925    }
  926
  927    fn release(&mut self, cx: &mut AppContext) {
  928        match &self.client_state {
  929            ProjectClientState::Local => {}
  930            ProjectClientState::Shared { .. } => {
  931                let _ = self.unshare_internal(cx);
  932            }
  933            ProjectClientState::Remote { remote_id, .. } => {
  934                let _ = self.client.send(proto::LeaveProject {
  935                    project_id: *remote_id,
  936                });
  937                self.disconnected_from_host_internal(cx);
  938            }
  939        }
  940    }
  941
  942    fn shutdown_language_servers(
  943        &mut self,
  944        _cx: &mut ModelContext<Self>,
  945    ) -> impl Future<Output = ()> {
  946        let shutdown_futures = self
  947            .language_servers
  948            .drain()
  949            .map(|(_, server_state)| async {
  950                use LanguageServerState::*;
  951                match server_state {
  952                    Running { server, .. } => server.shutdown()?.await,
  953                    Starting(task) => task.await?.shutdown()?.await,
  954                }
  955            })
  956            .collect::<Vec<_>>();
  957
  958        async move {
  959            futures::future::join_all(shutdown_futures).await;
  960        }
  961    }
  962
  963    #[cfg(any(test, feature = "test-support"))]
  964    pub async fn test(
  965        fs: Arc<dyn Fs>,
  966        root_paths: impl IntoIterator<Item = &Path>,
  967        cx: &mut gpui::TestAppContext,
  968    ) -> Model<Project> {
  969        use clock::FakeSystemClock;
  970
  971        let languages = LanguageRegistry::test(cx.executor());
  972        let clock = Arc::new(FakeSystemClock::default());
  973        let http_client = util::http::FakeHttpClient::with_404_response();
  974        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
  975        let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
  976        let project = cx.update(|cx| {
  977            Project::local(
  978                client,
  979                node_runtime::FakeNodeRuntime::new(),
  980                user_store,
  981                Arc::new(languages),
  982                fs,
  983                cx,
  984            )
  985        });
  986        for path in root_paths {
  987            let (tree, _) = project
  988                .update(cx, |project, cx| {
  989                    project.find_or_create_local_worktree(path, true, cx)
  990                })
  991                .await
  992                .unwrap();
  993            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
  994                .await;
  995        }
  996        project
  997    }
  998
  999    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 1000        let mut language_servers_to_start = Vec::new();
 1001        let mut language_formatters_to_check = Vec::new();
 1002        for buffer in self.opened_buffers.values() {
 1003            if let Some(buffer) = buffer.upgrade() {
 1004                let buffer = buffer.read(cx);
 1005                let buffer_file = File::from_dyn(buffer.file());
 1006                let buffer_language = buffer.language();
 1007                let settings = language_settings(buffer_language, buffer.file(), cx);
 1008                if let Some(language) = buffer_language {
 1009                    if settings.enable_language_server {
 1010                        if let Some(file) = buffer_file {
 1011                            language_servers_to_start
 1012                                .push((file.worktree.clone(), Arc::clone(language)));
 1013                        }
 1014                    }
 1015                    language_formatters_to_check.push((
 1016                        buffer_file.map(|f| f.worktree_id(cx)),
 1017                        Arc::clone(language),
 1018                        settings.clone(),
 1019                    ));
 1020                }
 1021            }
 1022        }
 1023
 1024        let mut language_servers_to_stop = Vec::new();
 1025        let mut language_servers_to_restart = Vec::new();
 1026        let languages = self.languages.to_vec();
 1027
 1028        let new_lsp_settings = ProjectSettings::get_global(cx).lsp.clone();
 1029        let current_lsp_settings = &self.current_lsp_settings;
 1030        for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 1031            let language = languages.iter().find_map(|l| {
 1032                let adapter = self
 1033                    .languages
 1034                    .lsp_adapters(l)
 1035                    .iter()
 1036                    .find(|adapter| &adapter.name == started_lsp_name)?
 1037                    .clone();
 1038                Some((l, adapter))
 1039            });
 1040            if let Some((language, adapter)) = language {
 1041                let worktree = self.worktree_for_id(*worktree_id, cx);
 1042                let file = worktree.as_ref().and_then(|tree| {
 1043                    tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
 1044                });
 1045                if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
 1046                    language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 1047                } else if let Some(worktree) = worktree {
 1048                    let server_name = &adapter.name.0;
 1049                    match (
 1050                        current_lsp_settings.get(server_name),
 1051                        new_lsp_settings.get(server_name),
 1052                    ) {
 1053                        (None, None) => {}
 1054                        (Some(_), None) | (None, Some(_)) => {
 1055                            language_servers_to_restart.push((worktree, Arc::clone(language)));
 1056                        }
 1057                        (Some(current_lsp_settings), Some(new_lsp_settings)) => {
 1058                            if current_lsp_settings != new_lsp_settings {
 1059                                language_servers_to_restart.push((worktree, Arc::clone(language)));
 1060                            }
 1061                        }
 1062                    }
 1063                }
 1064            }
 1065        }
 1066        self.current_lsp_settings = new_lsp_settings;
 1067
 1068        // Stop all newly-disabled language servers.
 1069        for (worktree_id, adapter_name) in language_servers_to_stop {
 1070            self.stop_language_server(worktree_id, adapter_name, cx)
 1071                .detach();
 1072        }
 1073
 1074        let mut prettier_plugins_by_worktree = HashMap::default();
 1075        for (worktree, language, settings) in language_formatters_to_check {
 1076            if let Some(plugins) =
 1077                prettier_support::prettier_plugins_for_language(&language, &settings)
 1078            {
 1079                prettier_plugins_by_worktree
 1080                    .entry(worktree)
 1081                    .or_insert_with(|| HashSet::default())
 1082                    .extend(plugins.iter().cloned());
 1083            }
 1084        }
 1085        for (worktree, prettier_plugins) in prettier_plugins_by_worktree {
 1086            self.install_default_prettier(worktree, prettier_plugins.into_iter(), cx);
 1087        }
 1088
 1089        // Start all the newly-enabled language servers.
 1090        for (worktree, language) in language_servers_to_start {
 1091            self.start_language_servers(&worktree, language, cx);
 1092        }
 1093
 1094        // Restart all language servers with changed initialization options.
 1095        for (worktree, language) in language_servers_to_restart {
 1096            self.restart_language_servers(worktree, language, cx);
 1097        }
 1098
 1099        if self.copilot_lsp_subscription.is_none() {
 1100            if let Some(copilot) = Copilot::global(cx) {
 1101                for buffer in self.opened_buffers.values() {
 1102                    if let Some(buffer) = buffer.upgrade() {
 1103                        self.register_buffer_with_copilot(&buffer, cx);
 1104                    }
 1105                }
 1106                self.copilot_lsp_subscription = Some(subscribe_for_copilot_events(&copilot, cx));
 1107            }
 1108        }
 1109
 1110        cx.notify();
 1111    }
 1112
 1113    pub fn buffer_for_id(&self, remote_id: BufferId) -> Option<Model<Buffer>> {
 1114        self.opened_buffers
 1115            .get(&remote_id)
 1116            .and_then(|buffer| buffer.upgrade())
 1117    }
 1118
 1119    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 1120        &self.languages
 1121    }
 1122
 1123    pub fn client(&self) -> Arc<Client> {
 1124        self.client.clone()
 1125    }
 1126
 1127    pub fn user_store(&self) -> Model<UserStore> {
 1128        self.user_store.clone()
 1129    }
 1130
 1131    pub fn opened_buffers(&self) -> Vec<Model<Buffer>> {
 1132        self.opened_buffers
 1133            .values()
 1134            .filter_map(|b| b.upgrade())
 1135            .collect()
 1136    }
 1137
 1138    #[cfg(any(test, feature = "test-support"))]
 1139    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 1140        let path = path.into();
 1141        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 1142            self.opened_buffers.iter().any(|(_, buffer)| {
 1143                if let Some(buffer) = buffer.upgrade() {
 1144                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 1145                        if file.worktree == worktree && file.path() == &path.path {
 1146                            return true;
 1147                        }
 1148                    }
 1149                }
 1150                false
 1151            })
 1152        } else {
 1153            false
 1154        }
 1155    }
 1156
 1157    pub fn fs(&self) -> &Arc<dyn Fs> {
 1158        &self.fs
 1159    }
 1160
 1161    pub fn remote_id(&self) -> Option<u64> {
 1162        match self.client_state {
 1163            ProjectClientState::Local => None,
 1164            ProjectClientState::Shared { remote_id, .. }
 1165            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
 1166        }
 1167    }
 1168
 1169    pub fn hosted_project_id(&self) -> Option<ProjectId> {
 1170        self.hosted_project_id
 1171    }
 1172
 1173    pub fn replica_id(&self) -> ReplicaId {
 1174        match self.client_state {
 1175            ProjectClientState::Remote { replica_id, .. } => replica_id,
 1176            _ => 0,
 1177        }
 1178    }
 1179
 1180    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
 1181        if let ProjectClientState::Shared { updates_tx, .. } = &mut self.client_state {
 1182            updates_tx
 1183                .unbounded_send(LocalProjectUpdate::WorktreesChanged)
 1184                .ok();
 1185        }
 1186        cx.notify();
 1187    }
 1188
 1189    pub fn task_inventory(&self) -> &Model<Inventory> {
 1190        &self.tasks
 1191    }
 1192
 1193    pub fn search_history(&self) -> &SearchHistory {
 1194        &self.search_history
 1195    }
 1196
 1197    pub fn search_history_mut(&mut self) -> &mut SearchHistory {
 1198        &mut self.search_history
 1199    }
 1200
 1201    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
 1202        &self.collaborators
 1203    }
 1204
 1205    pub fn host(&self) -> Option<&Collaborator> {
 1206        self.collaborators.values().find(|c| c.replica_id == 0)
 1207    }
 1208
 1209    /// Collect all worktrees, including ones that don't appear in the project panel
 1210    pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Model<Worktree>> {
 1211        self.worktrees
 1212            .iter()
 1213            .filter_map(move |worktree| worktree.upgrade())
 1214    }
 1215
 1216    /// Collect all user-visible worktrees, the ones that appear in the project panel
 1217    pub fn visible_worktrees<'a>(
 1218        &'a self,
 1219        cx: &'a AppContext,
 1220    ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
 1221        self.worktrees.iter().filter_map(|worktree| {
 1222            worktree.upgrade().and_then(|worktree| {
 1223                if worktree.read(cx).is_visible() {
 1224                    Some(worktree)
 1225                } else {
 1226                    None
 1227                }
 1228            })
 1229        })
 1230    }
 1231
 1232    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
 1233        self.visible_worktrees(cx)
 1234            .map(|tree| tree.read(cx).root_name())
 1235    }
 1236
 1237    pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
 1238        self.worktrees()
 1239            .find(|worktree| worktree.read(cx).id() == id)
 1240    }
 1241
 1242    pub fn worktree_for_entry(
 1243        &self,
 1244        entry_id: ProjectEntryId,
 1245        cx: &AppContext,
 1246    ) -> Option<Model<Worktree>> {
 1247        self.worktrees()
 1248            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
 1249    }
 1250
 1251    pub fn worktree_id_for_entry(
 1252        &self,
 1253        entry_id: ProjectEntryId,
 1254        cx: &AppContext,
 1255    ) -> Option<WorktreeId> {
 1256        self.worktree_for_entry(entry_id, cx)
 1257            .map(|worktree| worktree.read(cx).id())
 1258    }
 1259
 1260    pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &AppContext) -> Option<bool> {
 1261        paths
 1262            .iter()
 1263            .map(|path| self.visibility_for_path(path, cx))
 1264            .max()
 1265            .flatten()
 1266    }
 1267
 1268    pub fn visibility_for_path(&self, path: &Path, cx: &AppContext) -> Option<bool> {
 1269        self.worktrees()
 1270            .filter_map(|worktree| {
 1271                let worktree = worktree.read(cx);
 1272                worktree
 1273                    .as_local()?
 1274                    .contains_abs_path(path)
 1275                    .then(|| worktree.is_visible())
 1276            })
 1277            .max()
 1278    }
 1279
 1280    pub fn create_entry(
 1281        &mut self,
 1282        project_path: impl Into<ProjectPath>,
 1283        is_directory: bool,
 1284        cx: &mut ModelContext<Self>,
 1285    ) -> Task<Result<Option<Entry>>> {
 1286        let project_path = project_path.into();
 1287        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
 1288            return Task::ready(Ok(None));
 1289        };
 1290        if self.is_local() {
 1291            worktree.update(cx, |worktree, cx| {
 1292                worktree
 1293                    .as_local_mut()
 1294                    .unwrap()
 1295                    .create_entry(project_path.path, is_directory, cx)
 1296            })
 1297        } else {
 1298            let client = self.client.clone();
 1299            let project_id = self.remote_id().unwrap();
 1300            cx.spawn(move |_, mut cx| async move {
 1301                let response = client
 1302                    .request(proto::CreateProjectEntry {
 1303                        worktree_id: project_path.worktree_id.to_proto(),
 1304                        project_id,
 1305                        path: project_path.path.to_string_lossy().into(),
 1306                        is_directory,
 1307                    })
 1308                    .await?;
 1309                match response.entry {
 1310                    Some(entry) => worktree
 1311                        .update(&mut cx, |worktree, cx| {
 1312                            worktree.as_remote_mut().unwrap().insert_entry(
 1313                                entry,
 1314                                response.worktree_scan_id as usize,
 1315                                cx,
 1316                            )
 1317                        })?
 1318                        .await
 1319                        .map(Some),
 1320                    None => Ok(None),
 1321                }
 1322            })
 1323        }
 1324    }
 1325
 1326    pub fn copy_entry(
 1327        &mut self,
 1328        entry_id: ProjectEntryId,
 1329        new_path: impl Into<Arc<Path>>,
 1330        cx: &mut ModelContext<Self>,
 1331    ) -> Task<Result<Option<Entry>>> {
 1332        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
 1333            return Task::ready(Ok(None));
 1334        };
 1335        let new_path = new_path.into();
 1336        if self.is_local() {
 1337            worktree.update(cx, |worktree, cx| {
 1338                worktree
 1339                    .as_local_mut()
 1340                    .unwrap()
 1341                    .copy_entry(entry_id, new_path, cx)
 1342            })
 1343        } else {
 1344            let client = self.client.clone();
 1345            let project_id = self.remote_id().unwrap();
 1346
 1347            cx.spawn(move |_, mut cx| async move {
 1348                let response = client
 1349                    .request(proto::CopyProjectEntry {
 1350                        project_id,
 1351                        entry_id: entry_id.to_proto(),
 1352                        new_path: new_path.to_string_lossy().into(),
 1353                    })
 1354                    .await?;
 1355                match response.entry {
 1356                    Some(entry) => worktree
 1357                        .update(&mut cx, |worktree, cx| {
 1358                            worktree.as_remote_mut().unwrap().insert_entry(
 1359                                entry,
 1360                                response.worktree_scan_id as usize,
 1361                                cx,
 1362                            )
 1363                        })?
 1364                        .await
 1365                        .map(Some),
 1366                    None => Ok(None),
 1367                }
 1368            })
 1369        }
 1370    }
 1371
 1372    pub fn rename_entry(
 1373        &mut self,
 1374        entry_id: ProjectEntryId,
 1375        new_path: impl Into<Arc<Path>>,
 1376        cx: &mut ModelContext<Self>,
 1377    ) -> Task<Result<Option<Entry>>> {
 1378        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
 1379            return Task::ready(Ok(None));
 1380        };
 1381        let new_path = new_path.into();
 1382        if self.is_local() {
 1383            worktree.update(cx, |worktree, cx| {
 1384                worktree
 1385                    .as_local_mut()
 1386                    .unwrap()
 1387                    .rename_entry(entry_id, new_path, cx)
 1388            })
 1389        } else {
 1390            let client = self.client.clone();
 1391            let project_id = self.remote_id().unwrap();
 1392
 1393            cx.spawn(move |_, mut cx| async move {
 1394                let response = client
 1395                    .request(proto::RenameProjectEntry {
 1396                        project_id,
 1397                        entry_id: entry_id.to_proto(),
 1398                        new_path: new_path.to_string_lossy().into(),
 1399                    })
 1400                    .await?;
 1401                match response.entry {
 1402                    Some(entry) => worktree
 1403                        .update(&mut cx, |worktree, cx| {
 1404                            worktree.as_remote_mut().unwrap().insert_entry(
 1405                                entry,
 1406                                response.worktree_scan_id as usize,
 1407                                cx,
 1408                            )
 1409                        })?
 1410                        .await
 1411                        .map(Some),
 1412                    None => Ok(None),
 1413                }
 1414            })
 1415        }
 1416    }
 1417
 1418    pub fn delete_entry(
 1419        &mut self,
 1420        entry_id: ProjectEntryId,
 1421        cx: &mut ModelContext<Self>,
 1422    ) -> Option<Task<Result<()>>> {
 1423        let worktree = self.worktree_for_entry(entry_id, cx)?;
 1424
 1425        cx.emit(Event::DeletedEntry(entry_id));
 1426
 1427        if self.is_local() {
 1428            worktree.update(cx, |worktree, cx| {
 1429                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
 1430            })
 1431        } else {
 1432            let client = self.client.clone();
 1433            let project_id = self.remote_id().unwrap();
 1434            Some(cx.spawn(move |_, mut cx| async move {
 1435                let response = client
 1436                    .request(proto::DeleteProjectEntry {
 1437                        project_id,
 1438                        entry_id: entry_id.to_proto(),
 1439                    })
 1440                    .await?;
 1441                worktree
 1442                    .update(&mut cx, move |worktree, cx| {
 1443                        worktree.as_remote_mut().unwrap().delete_entry(
 1444                            entry_id,
 1445                            response.worktree_scan_id as usize,
 1446                            cx,
 1447                        )
 1448                    })?
 1449                    .await
 1450            }))
 1451        }
 1452    }
 1453
 1454    pub fn expand_entry(
 1455        &mut self,
 1456        worktree_id: WorktreeId,
 1457        entry_id: ProjectEntryId,
 1458        cx: &mut ModelContext<Self>,
 1459    ) -> Option<Task<Result<()>>> {
 1460        let worktree = self.worktree_for_id(worktree_id, cx)?;
 1461        if self.is_local() {
 1462            worktree.update(cx, |worktree, cx| {
 1463                worktree.as_local_mut().unwrap().expand_entry(entry_id, cx)
 1464            })
 1465        } else {
 1466            let worktree = worktree.downgrade();
 1467            let request = self.client.request(proto::ExpandProjectEntry {
 1468                project_id: self.remote_id().unwrap(),
 1469                entry_id: entry_id.to_proto(),
 1470            });
 1471            Some(cx.spawn(move |_, mut cx| async move {
 1472                let response = request.await?;
 1473                if let Some(worktree) = worktree.upgrade() {
 1474                    worktree
 1475                        .update(&mut cx, |worktree, _| {
 1476                            worktree
 1477                                .as_remote_mut()
 1478                                .unwrap()
 1479                                .wait_for_snapshot(response.worktree_scan_id as usize)
 1480                        })?
 1481                        .await?;
 1482                }
 1483                Ok(())
 1484            }))
 1485        }
 1486    }
 1487
 1488    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
 1489        if !matches!(self.client_state, ProjectClientState::Local) {
 1490            return Err(anyhow!("project was already shared"));
 1491        }
 1492        self.client_subscriptions.push(
 1493            self.client
 1494                .subscribe_to_entity(project_id)?
 1495                .set_model(&cx.handle(), &mut cx.to_async()),
 1496        );
 1497
 1498        for open_buffer in self.opened_buffers.values_mut() {
 1499            match open_buffer {
 1500                OpenBuffer::Strong(_) => {}
 1501                OpenBuffer::Weak(buffer) => {
 1502                    if let Some(buffer) = buffer.upgrade() {
 1503                        *open_buffer = OpenBuffer::Strong(buffer);
 1504                    }
 1505                }
 1506                OpenBuffer::Operations(_) => unreachable!(),
 1507            }
 1508        }
 1509
 1510        for worktree_handle in self.worktrees.iter_mut() {
 1511            match worktree_handle {
 1512                WorktreeHandle::Strong(_) => {}
 1513                WorktreeHandle::Weak(worktree) => {
 1514                    if let Some(worktree) = worktree.upgrade() {
 1515                        *worktree_handle = WorktreeHandle::Strong(worktree);
 1516                    }
 1517                }
 1518            }
 1519        }
 1520
 1521        for (server_id, status) in &self.language_server_statuses {
 1522            self.client
 1523                .send(proto::StartLanguageServer {
 1524                    project_id,
 1525                    server: Some(proto::LanguageServer {
 1526                        id: server_id.0 as u64,
 1527                        name: status.name.clone(),
 1528                    }),
 1529                })
 1530                .log_err();
 1531        }
 1532
 1533        let store = cx.global::<SettingsStore>();
 1534        for worktree in self.worktrees() {
 1535            let worktree_id = worktree.read(cx).id().to_proto();
 1536            for (path, content) in store.local_settings(worktree.entity_id().as_u64() as usize) {
 1537                self.client
 1538                    .send(proto::UpdateWorktreeSettings {
 1539                        project_id,
 1540                        worktree_id,
 1541                        path: path.to_string_lossy().into(),
 1542                        content: Some(content),
 1543                    })
 1544                    .log_err();
 1545            }
 1546        }
 1547
 1548        let (updates_tx, mut updates_rx) = mpsc::unbounded();
 1549        let client = self.client.clone();
 1550        self.client_state = ProjectClientState::Shared {
 1551            remote_id: project_id,
 1552            updates_tx,
 1553            _send_updates: cx.spawn(move |this, mut cx| async move {
 1554                while let Some(update) = updates_rx.next().await {
 1555                    match update {
 1556                        LocalProjectUpdate::WorktreesChanged => {
 1557                            let worktrees = this.update(&mut cx, |this, _cx| {
 1558                                this.worktrees().collect::<Vec<_>>()
 1559                            })?;
 1560                            let update_project = this
 1561                                .update(&mut cx, |this, cx| {
 1562                                    this.client.request(proto::UpdateProject {
 1563                                        project_id,
 1564                                        worktrees: this.worktree_metadata_protos(cx),
 1565                                    })
 1566                                })?
 1567                                .await;
 1568                            if update_project.is_ok() {
 1569                                for worktree in worktrees {
 1570                                    worktree.update(&mut cx, |worktree, cx| {
 1571                                        let worktree = worktree.as_local_mut().unwrap();
 1572                                        worktree.share(project_id, cx).detach_and_log_err(cx)
 1573                                    })?;
 1574                                }
 1575                            }
 1576                        }
 1577                        LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
 1578                            let buffer = this.update(&mut cx, |this, _| {
 1579                                let buffer = this.opened_buffers.get(&buffer_id).unwrap();
 1580                                let shared_buffers =
 1581                                    this.shared_buffers.entry(peer_id).or_default();
 1582                                if shared_buffers.insert(buffer_id) {
 1583                                    if let OpenBuffer::Strong(buffer) = buffer {
 1584                                        Some(buffer.clone())
 1585                                    } else {
 1586                                        None
 1587                                    }
 1588                                } else {
 1589                                    None
 1590                                }
 1591                            })?;
 1592
 1593                            let Some(buffer) = buffer else { continue };
 1594                            let operations =
 1595                                buffer.update(&mut cx, |b, cx| b.serialize_ops(None, cx))?;
 1596                            let operations = operations.await;
 1597                            let state = buffer.update(&mut cx, |buffer, _| buffer.to_proto())?;
 1598
 1599                            let initial_state = proto::CreateBufferForPeer {
 1600                                project_id,
 1601                                peer_id: Some(peer_id),
 1602                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
 1603                            };
 1604                            if client.send(initial_state).log_err().is_some() {
 1605                                let client = client.clone();
 1606                                cx.background_executor()
 1607                                    .spawn(async move {
 1608                                        let mut chunks = split_operations(operations).peekable();
 1609                                        while let Some(chunk) = chunks.next() {
 1610                                            let is_last = chunks.peek().is_none();
 1611                                            client.send(proto::CreateBufferForPeer {
 1612                                                project_id,
 1613                                                peer_id: Some(peer_id),
 1614                                                variant: Some(
 1615                                                    proto::create_buffer_for_peer::Variant::Chunk(
 1616                                                        proto::BufferChunk {
 1617                                                            buffer_id: buffer_id.into(),
 1618                                                            operations: chunk,
 1619                                                            is_last,
 1620                                                        },
 1621                                                    ),
 1622                                                ),
 1623                                            })?;
 1624                                        }
 1625                                        anyhow::Ok(())
 1626                                    })
 1627                                    .await
 1628                                    .log_err();
 1629                            }
 1630                        }
 1631                    }
 1632                }
 1633                Ok(())
 1634            }),
 1635        };
 1636
 1637        self.metadata_changed(cx);
 1638        cx.emit(Event::RemoteIdChanged(Some(project_id)));
 1639        cx.notify();
 1640        Ok(())
 1641    }
 1642
 1643    pub fn reshared(
 1644        &mut self,
 1645        message: proto::ResharedProject,
 1646        cx: &mut ModelContext<Self>,
 1647    ) -> Result<()> {
 1648        self.shared_buffers.clear();
 1649        self.set_collaborators_from_proto(message.collaborators, cx)?;
 1650        self.metadata_changed(cx);
 1651        Ok(())
 1652    }
 1653
 1654    pub fn rejoined(
 1655        &mut self,
 1656        message: proto::RejoinedProject,
 1657        message_id: u32,
 1658        cx: &mut ModelContext<Self>,
 1659    ) -> Result<()> {
 1660        cx.update_global::<SettingsStore, _>(|store, cx| {
 1661            for worktree in &self.worktrees {
 1662                store
 1663                    .clear_local_settings(worktree.handle_id(), cx)
 1664                    .log_err();
 1665            }
 1666        });
 1667
 1668        self.join_project_response_message_id = message_id;
 1669        self.set_worktrees_from_proto(message.worktrees, cx)?;
 1670        self.set_collaborators_from_proto(message.collaborators, cx)?;
 1671        self.language_server_statuses = message
 1672            .language_servers
 1673            .into_iter()
 1674            .map(|server| {
 1675                (
 1676                    LanguageServerId(server.id as usize),
 1677                    LanguageServerStatus {
 1678                        name: server.name,
 1679                        pending_work: Default::default(),
 1680                        has_pending_diagnostic_updates: false,
 1681                        progress_tokens: Default::default(),
 1682                    },
 1683                )
 1684            })
 1685            .collect();
 1686        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
 1687            .unwrap();
 1688        cx.notify();
 1689        Ok(())
 1690    }
 1691
 1692    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
 1693        self.unshare_internal(cx)?;
 1694        self.metadata_changed(cx);
 1695        cx.notify();
 1696        Ok(())
 1697    }
 1698
 1699    fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
 1700        if self.is_remote() {
 1701            return Err(anyhow!("attempted to unshare a remote project"));
 1702        }
 1703
 1704        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
 1705            self.client_state = ProjectClientState::Local;
 1706            self.collaborators.clear();
 1707            self.shared_buffers.clear();
 1708            self.client_subscriptions.clear();
 1709
 1710            for worktree_handle in self.worktrees.iter_mut() {
 1711                if let WorktreeHandle::Strong(worktree) = worktree_handle {
 1712                    let is_visible = worktree.update(cx, |worktree, _| {
 1713                        worktree.as_local_mut().unwrap().unshare();
 1714                        worktree.is_visible()
 1715                    });
 1716                    if !is_visible {
 1717                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
 1718                    }
 1719                }
 1720            }
 1721
 1722            for open_buffer in self.opened_buffers.values_mut() {
 1723                // Wake up any tasks waiting for peers' edits to this buffer.
 1724                if let Some(buffer) = open_buffer.upgrade() {
 1725                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
 1726                }
 1727
 1728                if let OpenBuffer::Strong(buffer) = open_buffer {
 1729                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
 1730                }
 1731            }
 1732
 1733            self.client.send(proto::UnshareProject {
 1734                project_id: remote_id,
 1735            })?;
 1736
 1737            Ok(())
 1738        } else {
 1739            Err(anyhow!("attempted to unshare an unshared project"))
 1740        }
 1741    }
 1742
 1743    pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
 1744        self.disconnected_from_host_internal(cx);
 1745        cx.emit(Event::DisconnectedFromHost);
 1746        cx.notify();
 1747    }
 1748
 1749    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut ModelContext<Self>) {
 1750        let new_capability =
 1751            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
 1752                Capability::ReadWrite
 1753            } else {
 1754                Capability::ReadOnly
 1755            };
 1756        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
 1757            if *capability == new_capability {
 1758                return;
 1759            }
 1760
 1761            *capability = new_capability;
 1762            for buffer in self.opened_buffers() {
 1763                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
 1764            }
 1765        }
 1766    }
 1767
 1768    fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
 1769        if let ProjectClientState::Remote {
 1770            sharing_has_stopped,
 1771            ..
 1772        } = &mut self.client_state
 1773        {
 1774            *sharing_has_stopped = true;
 1775
 1776            self.collaborators.clear();
 1777
 1778            for worktree in &self.worktrees {
 1779                if let Some(worktree) = worktree.upgrade() {
 1780                    worktree.update(cx, |worktree, _| {
 1781                        if let Some(worktree) = worktree.as_remote_mut() {
 1782                            worktree.disconnected_from_host();
 1783                        }
 1784                    });
 1785                }
 1786            }
 1787
 1788            for open_buffer in self.opened_buffers.values_mut() {
 1789                // Wake up any tasks waiting for peers' edits to this buffer.
 1790                if let Some(buffer) = open_buffer.upgrade() {
 1791                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
 1792                }
 1793
 1794                if let OpenBuffer::Strong(buffer) = open_buffer {
 1795                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
 1796                }
 1797            }
 1798
 1799            // Wake up all futures currently waiting on a buffer to get opened,
 1800            // to give them a chance to fail now that we've disconnected.
 1801            self.loading_buffers.clear();
 1802            // self.opened_buffer.send(OpenedBufferEvent::Disconnected);
 1803        }
 1804    }
 1805
 1806    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
 1807        cx.emit(Event::Closed);
 1808    }
 1809
 1810    pub fn is_disconnected(&self) -> bool {
 1811        match &self.client_state {
 1812            ProjectClientState::Remote {
 1813                sharing_has_stopped,
 1814                ..
 1815            } => *sharing_has_stopped,
 1816            _ => false,
 1817        }
 1818    }
 1819
 1820    pub fn capability(&self) -> Capability {
 1821        match &self.client_state {
 1822            ProjectClientState::Remote { capability, .. } => *capability,
 1823            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
 1824        }
 1825    }
 1826
 1827    pub fn is_read_only(&self) -> bool {
 1828        self.is_disconnected() || self.capability() == Capability::ReadOnly
 1829    }
 1830
 1831    pub fn is_local(&self) -> bool {
 1832        match &self.client_state {
 1833            ProjectClientState::Local | ProjectClientState::Shared { .. } => true,
 1834            ProjectClientState::Remote { .. } => false,
 1835        }
 1836    }
 1837
 1838    pub fn is_remote(&self) -> bool {
 1839        !self.is_local()
 1840    }
 1841
 1842    pub fn create_buffer(
 1843        &mut self,
 1844        text: &str,
 1845        language: Option<Arc<Language>>,
 1846        cx: &mut ModelContext<Self>,
 1847    ) -> Result<Model<Buffer>> {
 1848        if self.is_remote() {
 1849            return Err(anyhow!("creating buffers as a guest is not supported yet"));
 1850        }
 1851        let id = self.next_buffer_id.next();
 1852        let buffer = cx.new_model(|cx| {
 1853            Buffer::new(self.replica_id(), id, text)
 1854                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
 1855        });
 1856        self.register_buffer(&buffer, cx)?;
 1857        Ok(buffer)
 1858    }
 1859
 1860    pub fn open_path(
 1861        &mut self,
 1862        path: ProjectPath,
 1863        cx: &mut ModelContext<Self>,
 1864    ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
 1865        let task = self.open_buffer(path.clone(), cx);
 1866        cx.spawn(move |_, cx| async move {
 1867            let buffer = task.await?;
 1868            let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
 1869                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
 1870            })?;
 1871
 1872            let buffer: &AnyModel = &buffer;
 1873            Ok((project_entry_id, buffer.clone()))
 1874        })
 1875    }
 1876
 1877    pub fn open_local_buffer(
 1878        &mut self,
 1879        abs_path: impl AsRef<Path>,
 1880        cx: &mut ModelContext<Self>,
 1881    ) -> Task<Result<Model<Buffer>>> {
 1882        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
 1883            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
 1884        } else {
 1885            Task::ready(Err(anyhow!("no such path")))
 1886        }
 1887    }
 1888
 1889    pub fn open_buffer(
 1890        &mut self,
 1891        path: impl Into<ProjectPath>,
 1892        cx: &mut ModelContext<Self>,
 1893    ) -> Task<Result<Model<Buffer>>> {
 1894        let project_path = path.into();
 1895        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
 1896            worktree
 1897        } else {
 1898            return Task::ready(Err(anyhow!("no such worktree")));
 1899        };
 1900
 1901        // If there is already a buffer for the given path, then return it.
 1902        let existing_buffer = self.get_open_buffer(&project_path, cx);
 1903        if let Some(existing_buffer) = existing_buffer {
 1904            return Task::ready(Ok(existing_buffer));
 1905        }
 1906
 1907        let loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
 1908            // If the given path is already being loaded, then wait for that existing
 1909            // task to complete and return the same buffer.
 1910            hash_map::Entry::Occupied(e) => e.get().clone(),
 1911
 1912            // Otherwise, record the fact that this path is now being loaded.
 1913            hash_map::Entry::Vacant(entry) => {
 1914                let (mut tx, rx) = postage::watch::channel();
 1915                entry.insert(rx.clone());
 1916
 1917                let project_path = project_path.clone();
 1918                let load_buffer = if worktree.read(cx).is_local() {
 1919                    self.open_local_buffer_internal(project_path.path.clone(), worktree, cx)
 1920                } else {
 1921                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
 1922                };
 1923
 1924                cx.spawn(move |this, mut cx| async move {
 1925                    let load_result = load_buffer.await;
 1926                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
 1927                        // Record the fact that the buffer is no longer loading.
 1928                        this.loading_buffers_by_path.remove(&project_path);
 1929                        let buffer = load_result.map_err(Arc::new)?;
 1930                        Ok(buffer)
 1931                    })?);
 1932                    anyhow::Ok(())
 1933                })
 1934                .detach();
 1935                rx
 1936            }
 1937        };
 1938
 1939        cx.background_executor().spawn(async move {
 1940            wait_for_loading_buffer(loading_watch)
 1941                .await
 1942                .map_err(|e| e.cloned())
 1943        })
 1944    }
 1945
 1946    fn open_local_buffer_internal(
 1947        &mut self,
 1948        path: Arc<Path>,
 1949        worktree: Model<Worktree>,
 1950        cx: &mut ModelContext<Self>,
 1951    ) -> Task<Result<Model<Buffer>>> {
 1952        let buffer_id = self.next_buffer_id.next();
 1953        let load_buffer = worktree.update(cx, |worktree, cx| {
 1954            let worktree = worktree.as_local_mut().unwrap();
 1955            worktree.load_buffer(buffer_id, &path, cx)
 1956        });
 1957        fn is_not_found_error(error: &anyhow::Error) -> bool {
 1958            error
 1959                .root_cause()
 1960                .downcast_ref::<io::Error>()
 1961                .is_some_and(|err| err.kind() == io::ErrorKind::NotFound)
 1962        }
 1963        cx.spawn(move |this, mut cx| async move {
 1964            let buffer = match load_buffer.await {
 1965                Ok(buffer) => Ok(buffer),
 1966                Err(error) if is_not_found_error(&error) => {
 1967                    worktree.update(&mut cx, |worktree, cx| {
 1968                        let worktree = worktree.as_local_mut().unwrap();
 1969                        worktree.new_buffer(buffer_id, path, cx)
 1970                    })
 1971                }
 1972                Err(e) => Err(e),
 1973            }?;
 1974            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))??;
 1975            Ok(buffer)
 1976        })
 1977    }
 1978
 1979    fn open_remote_buffer_internal(
 1980        &mut self,
 1981        path: &Arc<Path>,
 1982        worktree: &Model<Worktree>,
 1983        cx: &mut ModelContext<Self>,
 1984    ) -> Task<Result<Model<Buffer>>> {
 1985        let rpc = self.client.clone();
 1986        let project_id = self.remote_id().unwrap();
 1987        let remote_worktree_id = worktree.read(cx).id();
 1988        let path = path.clone();
 1989        let path_string = path.to_string_lossy().to_string();
 1990        cx.spawn(move |this, mut cx| async move {
 1991            let response = rpc
 1992                .request(proto::OpenBufferByPath {
 1993                    project_id,
 1994                    worktree_id: remote_worktree_id.to_proto(),
 1995                    path: path_string,
 1996                })
 1997                .await?;
 1998            let buffer_id = BufferId::new(response.buffer_id)?;
 1999            this.update(&mut cx, |this, cx| {
 2000                this.wait_for_remote_buffer(buffer_id, cx)
 2001            })?
 2002            .await
 2003        })
 2004    }
 2005
 2006    /// LanguageServerName is owned, because it is inserted into a map
 2007    pub fn open_local_buffer_via_lsp(
 2008        &mut self,
 2009        abs_path: lsp::Url,
 2010        language_server_id: LanguageServerId,
 2011        language_server_name: LanguageServerName,
 2012        cx: &mut ModelContext<Self>,
 2013    ) -> Task<Result<Model<Buffer>>> {
 2014        cx.spawn(move |this, mut cx| async move {
 2015            let abs_path = abs_path
 2016                .to_file_path()
 2017                .map_err(|_| anyhow!("can't convert URI to path"))?;
 2018            let (worktree, relative_path) = if let Some(result) =
 2019                this.update(&mut cx, |this, cx| this.find_local_worktree(&abs_path, cx))?
 2020            {
 2021                result
 2022            } else {
 2023                let worktree = this
 2024                    .update(&mut cx, |this, cx| {
 2025                        this.create_local_worktree(&abs_path, false, cx)
 2026                    })?
 2027                    .await?;
 2028                this.update(&mut cx, |this, cx| {
 2029                    this.language_server_ids.insert(
 2030                        (worktree.read(cx).id(), language_server_name),
 2031                        language_server_id,
 2032                    );
 2033                })
 2034                .ok();
 2035                (worktree, PathBuf::new())
 2036            };
 2037
 2038            let project_path = ProjectPath {
 2039                worktree_id: worktree.update(&mut cx, |worktree, _| worktree.id())?,
 2040                path: relative_path.into(),
 2041            };
 2042            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))?
 2043                .await
 2044        })
 2045    }
 2046
 2047    pub fn open_buffer_by_id(
 2048        &mut self,
 2049        id: BufferId,
 2050        cx: &mut ModelContext<Self>,
 2051    ) -> Task<Result<Model<Buffer>>> {
 2052        if let Some(buffer) = self.buffer_for_id(id) {
 2053            Task::ready(Ok(buffer))
 2054        } else if self.is_local() {
 2055            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
 2056        } else if let Some(project_id) = self.remote_id() {
 2057            let request = self.client.request(proto::OpenBufferById {
 2058                project_id,
 2059                id: id.into(),
 2060            });
 2061            cx.spawn(move |this, mut cx| async move {
 2062                let buffer_id = BufferId::new(request.await?.buffer_id)?;
 2063                this.update(&mut cx, |this, cx| {
 2064                    this.wait_for_remote_buffer(buffer_id, cx)
 2065                })?
 2066                .await
 2067            })
 2068        } else {
 2069            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
 2070        }
 2071    }
 2072
 2073    pub fn save_buffers(
 2074        &self,
 2075        buffers: HashSet<Model<Buffer>>,
 2076        cx: &mut ModelContext<Self>,
 2077    ) -> Task<Result<()>> {
 2078        cx.spawn(move |this, mut cx| async move {
 2079            let save_tasks = buffers.into_iter().filter_map(|buffer| {
 2080                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
 2081                    .ok()
 2082            });
 2083            try_join_all(save_tasks).await?;
 2084            Ok(())
 2085        })
 2086    }
 2087
 2088    pub fn save_buffer(
 2089        &self,
 2090        buffer: Model<Buffer>,
 2091        cx: &mut ModelContext<Self>,
 2092    ) -> Task<Result<()>> {
 2093        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 2094            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
 2095        };
 2096        let worktree = file.worktree.clone();
 2097        let path = file.path.clone();
 2098        worktree.update(cx, |worktree, cx| match worktree {
 2099            Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
 2100            Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
 2101        })
 2102    }
 2103
 2104    pub fn save_buffer_as(
 2105        &mut self,
 2106        buffer: Model<Buffer>,
 2107        abs_path: PathBuf,
 2108        cx: &mut ModelContext<Self>,
 2109    ) -> Task<Result<()>> {
 2110        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
 2111        let old_file = File::from_dyn(buffer.read(cx).file())
 2112            .filter(|f| f.is_local())
 2113            .cloned();
 2114        cx.spawn(move |this, mut cx| async move {
 2115            if let Some(old_file) = &old_file {
 2116                this.update(&mut cx, |this, cx| {
 2117                    this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
 2118                })?;
 2119            }
 2120            let (worktree, path) = worktree_task.await?;
 2121            worktree
 2122                .update(&mut cx, |worktree, cx| match worktree {
 2123                    Worktree::Local(worktree) => {
 2124                        worktree.save_buffer(buffer.clone(), path.into(), true, cx)
 2125                    }
 2126                    Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
 2127                })?
 2128                .await?;
 2129
 2130            this.update(&mut cx, |this, cx| {
 2131                this.detect_language_for_buffer(&buffer, cx);
 2132                this.register_buffer_with_language_servers(&buffer, cx);
 2133            })?;
 2134            Ok(())
 2135        })
 2136    }
 2137
 2138    pub fn get_open_buffer(
 2139        &mut self,
 2140        path: &ProjectPath,
 2141        cx: &mut ModelContext<Self>,
 2142    ) -> Option<Model<Buffer>> {
 2143        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
 2144        self.opened_buffers.values().find_map(|buffer| {
 2145            let buffer = buffer.upgrade()?;
 2146            let file = File::from_dyn(buffer.read(cx).file())?;
 2147            if file.worktree == worktree && file.path() == &path.path {
 2148                Some(buffer)
 2149            } else {
 2150                None
 2151            }
 2152        })
 2153    }
 2154
 2155    fn register_buffer(
 2156        &mut self,
 2157        buffer: &Model<Buffer>,
 2158        cx: &mut ModelContext<Self>,
 2159    ) -> Result<()> {
 2160        self.request_buffer_diff_recalculation(buffer, cx);
 2161        buffer.update(cx, |buffer, _| {
 2162            buffer.set_language_registry(self.languages.clone())
 2163        });
 2164
 2165        let remote_id = buffer.read(cx).remote_id();
 2166        let is_remote = self.is_remote();
 2167        let open_buffer = if is_remote || self.is_shared() {
 2168            OpenBuffer::Strong(buffer.clone())
 2169        } else {
 2170            OpenBuffer::Weak(buffer.downgrade())
 2171        };
 2172
 2173        match self.opened_buffers.entry(remote_id) {
 2174            hash_map::Entry::Vacant(entry) => {
 2175                entry.insert(open_buffer);
 2176            }
 2177            hash_map::Entry::Occupied(mut entry) => {
 2178                if let OpenBuffer::Operations(operations) = entry.get_mut() {
 2179                    buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
 2180                } else if entry.get().upgrade().is_some() {
 2181                    if is_remote {
 2182                        return Ok(());
 2183                    } else {
 2184                        debug_panic!("buffer {} was already registered", remote_id);
 2185                        Err(anyhow!("buffer {} was already registered", remote_id))?;
 2186                    }
 2187                }
 2188                entry.insert(open_buffer);
 2189            }
 2190        }
 2191        cx.subscribe(buffer, |this, buffer, event, cx| {
 2192            this.on_buffer_event(buffer, event, cx);
 2193        })
 2194        .detach();
 2195
 2196        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 2197            if file.is_local {
 2198                self.local_buffer_ids_by_path.insert(
 2199                    ProjectPath {
 2200                        worktree_id: file.worktree_id(cx),
 2201                        path: file.path.clone(),
 2202                    },
 2203                    remote_id,
 2204                );
 2205
 2206                if let Some(entry_id) = file.entry_id {
 2207                    self.local_buffer_ids_by_entry_id
 2208                        .insert(entry_id, remote_id);
 2209                }
 2210            }
 2211        }
 2212
 2213        self.detect_language_for_buffer(buffer, cx);
 2214        self.register_buffer_with_language_servers(buffer, cx);
 2215        self.register_buffer_with_copilot(buffer, cx);
 2216        cx.observe_release(buffer, |this, buffer, cx| {
 2217            if let Some(file) = File::from_dyn(buffer.file()) {
 2218                if file.is_local() {
 2219                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
 2220                    for server in this.language_servers_for_buffer(buffer, cx) {
 2221                        server
 2222                            .1
 2223                            .notify::<lsp::notification::DidCloseTextDocument>(
 2224                                lsp::DidCloseTextDocumentParams {
 2225                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
 2226                                },
 2227                            )
 2228                            .log_err();
 2229                    }
 2230                }
 2231            }
 2232        })
 2233        .detach();
 2234
 2235        if let Some(senders) = self.loading_buffers.remove(&remote_id) {
 2236            for sender in senders {
 2237                sender.send(Ok(buffer.clone())).ok();
 2238            }
 2239        }
 2240        Ok(())
 2241    }
 2242
 2243    fn register_buffer_with_language_servers(
 2244        &mut self,
 2245        buffer_handle: &Model<Buffer>,
 2246        cx: &mut ModelContext<Self>,
 2247    ) {
 2248        let buffer = buffer_handle.read(cx);
 2249        let buffer_id = buffer.remote_id();
 2250
 2251        if let Some(file) = File::from_dyn(buffer.file()) {
 2252            if !file.is_local() {
 2253                return;
 2254            }
 2255
 2256            let abs_path = file.abs_path(cx);
 2257            let uri = lsp::Url::from_file_path(&abs_path)
 2258                .unwrap_or_else(|()| panic!("Failed to register file {abs_path:?}"));
 2259            let initial_snapshot = buffer.text_snapshot();
 2260            let language = buffer.language().cloned();
 2261            let worktree_id = file.worktree_id(cx);
 2262
 2263            if let Some(local_worktree) = file.worktree.read(cx).as_local() {
 2264                for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
 2265                    self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
 2266                        .log_err();
 2267                }
 2268            }
 2269
 2270            if let Some(language) = language {
 2271                for adapter in self.languages.lsp_adapters(&language) {
 2272                    let language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
 2273                    let server = self
 2274                        .language_server_ids
 2275                        .get(&(worktree_id, adapter.name.clone()))
 2276                        .and_then(|id| self.language_servers.get(id))
 2277                        .and_then(|server_state| {
 2278                            if let LanguageServerState::Running { server, .. } = server_state {
 2279                                Some(server.clone())
 2280                            } else {
 2281                                None
 2282                            }
 2283                        });
 2284                    let server = match server {
 2285                        Some(server) => server,
 2286                        None => continue,
 2287                    };
 2288
 2289                    server
 2290                        .notify::<lsp::notification::DidOpenTextDocument>(
 2291                            lsp::DidOpenTextDocumentParams {
 2292                                text_document: lsp::TextDocumentItem::new(
 2293                                    uri.clone(),
 2294                                    language_id.unwrap_or_default(),
 2295                                    0,
 2296                                    initial_snapshot.text(),
 2297                                ),
 2298                            },
 2299                        )
 2300                        .log_err();
 2301
 2302                    buffer_handle.update(cx, |buffer, cx| {
 2303                        buffer.set_completion_triggers(
 2304                            server
 2305                                .capabilities()
 2306                                .completion_provider
 2307                                .as_ref()
 2308                                .and_then(|provider| provider.trigger_characters.clone())
 2309                                .unwrap_or_default(),
 2310                            cx,
 2311                        );
 2312                    });
 2313
 2314                    let snapshot = LspBufferSnapshot {
 2315                        version: 0,
 2316                        snapshot: initial_snapshot.clone(),
 2317                    };
 2318                    self.buffer_snapshots
 2319                        .entry(buffer_id)
 2320                        .or_default()
 2321                        .insert(server.server_id(), vec![snapshot]);
 2322                }
 2323            }
 2324        }
 2325    }
 2326
 2327    fn unregister_buffer_from_language_servers(
 2328        &mut self,
 2329        buffer: &Model<Buffer>,
 2330        old_file: &File,
 2331        cx: &mut ModelContext<Self>,
 2332    ) {
 2333        let old_path = match old_file.as_local() {
 2334            Some(local) => local.abs_path(cx),
 2335            None => return,
 2336        };
 2337
 2338        buffer.update(cx, |buffer, cx| {
 2339            let worktree_id = old_file.worktree_id(cx);
 2340            let ids = &self.language_server_ids;
 2341
 2342            if let Some(language) = buffer.language().cloned() {
 2343                for adapter in self.languages.lsp_adapters(&language) {
 2344                    if let Some(server_id) = ids.get(&(worktree_id, adapter.name.clone())) {
 2345                        buffer.update_diagnostics(*server_id, Default::default(), cx);
 2346                    }
 2347                }
 2348            }
 2349
 2350            self.buffer_snapshots.remove(&buffer.remote_id());
 2351            let file_url = lsp::Url::from_file_path(old_path).unwrap();
 2352            for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
 2353                language_server
 2354                    .notify::<lsp::notification::DidCloseTextDocument>(
 2355                        lsp::DidCloseTextDocumentParams {
 2356                            text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
 2357                        },
 2358                    )
 2359                    .log_err();
 2360            }
 2361        });
 2362    }
 2363
 2364    fn register_buffer_with_copilot(
 2365        &self,
 2366        buffer_handle: &Model<Buffer>,
 2367        cx: &mut ModelContext<Self>,
 2368    ) {
 2369        if let Some(copilot) = Copilot::global(cx) {
 2370            copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
 2371        }
 2372    }
 2373
 2374    async fn send_buffer_ordered_messages(
 2375        this: WeakModel<Self>,
 2376        rx: UnboundedReceiver<BufferOrderedMessage>,
 2377        mut cx: AsyncAppContext,
 2378    ) -> Result<()> {
 2379        const MAX_BATCH_SIZE: usize = 128;
 2380
 2381        let mut operations_by_buffer_id = HashMap::default();
 2382        async fn flush_operations(
 2383            this: &WeakModel<Project>,
 2384            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
 2385            needs_resync_with_host: &mut bool,
 2386            is_local: bool,
 2387            cx: &mut AsyncAppContext,
 2388        ) -> Result<()> {
 2389            for (buffer_id, operations) in operations_by_buffer_id.drain() {
 2390                let request = this.update(cx, |this, _| {
 2391                    let project_id = this.remote_id()?;
 2392                    Some(this.client.request(proto::UpdateBuffer {
 2393                        buffer_id: buffer_id.into(),
 2394                        project_id,
 2395                        operations,
 2396                    }))
 2397                })?;
 2398                if let Some(request) = request {
 2399                    if request.await.is_err() && !is_local {
 2400                        *needs_resync_with_host = true;
 2401                        break;
 2402                    }
 2403                }
 2404            }
 2405            Ok(())
 2406        }
 2407
 2408        let mut needs_resync_with_host = false;
 2409        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
 2410
 2411        while let Some(changes) = changes.next().await {
 2412            let is_local = this.update(&mut cx, |this, _| this.is_local())?;
 2413
 2414            for change in changes {
 2415                match change {
 2416                    BufferOrderedMessage::Operation {
 2417                        buffer_id,
 2418                        operation,
 2419                    } => {
 2420                        if needs_resync_with_host {
 2421                            continue;
 2422                        }
 2423
 2424                        operations_by_buffer_id
 2425                            .entry(buffer_id)
 2426                            .or_insert(Vec::new())
 2427                            .push(operation);
 2428                    }
 2429
 2430                    BufferOrderedMessage::Resync => {
 2431                        operations_by_buffer_id.clear();
 2432                        if this
 2433                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
 2434                            .await
 2435                            .is_ok()
 2436                        {
 2437                            needs_resync_with_host = false;
 2438                        }
 2439                    }
 2440
 2441                    BufferOrderedMessage::LanguageServerUpdate {
 2442                        language_server_id,
 2443                        message,
 2444                    } => {
 2445                        flush_operations(
 2446                            &this,
 2447                            &mut operations_by_buffer_id,
 2448                            &mut needs_resync_with_host,
 2449                            is_local,
 2450                            &mut cx,
 2451                        )
 2452                        .await?;
 2453
 2454                        this.update(&mut cx, |this, _| {
 2455                            if let Some(project_id) = this.remote_id() {
 2456                                this.client
 2457                                    .send(proto::UpdateLanguageServer {
 2458                                        project_id,
 2459                                        language_server_id: language_server_id.0 as u64,
 2460                                        variant: Some(message),
 2461                                    })
 2462                                    .log_err();
 2463                            }
 2464                        })?;
 2465                    }
 2466                }
 2467            }
 2468
 2469            flush_operations(
 2470                &this,
 2471                &mut operations_by_buffer_id,
 2472                &mut needs_resync_with_host,
 2473                is_local,
 2474                &mut cx,
 2475            )
 2476            .await?;
 2477        }
 2478
 2479        Ok(())
 2480    }
 2481
 2482    fn on_buffer_event(
 2483        &mut self,
 2484        buffer: Model<Buffer>,
 2485        event: &BufferEvent,
 2486        cx: &mut ModelContext<Self>,
 2487    ) -> Option<()> {
 2488        if matches!(
 2489            event,
 2490            BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
 2491        ) {
 2492            self.request_buffer_diff_recalculation(&buffer, cx);
 2493        }
 2494
 2495        match event {
 2496            BufferEvent::Operation(operation) => {
 2497                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
 2498                    buffer_id: buffer.read(cx).remote_id(),
 2499                    operation: language::proto::serialize_operation(operation),
 2500                })
 2501                .ok();
 2502            }
 2503
 2504            BufferEvent::Edited { .. } => {
 2505                let buffer = buffer.read(cx);
 2506                let file = File::from_dyn(buffer.file())?;
 2507                let abs_path = file.as_local()?.abs_path(cx);
 2508                let uri = lsp::Url::from_file_path(abs_path).unwrap();
 2509                let next_snapshot = buffer.text_snapshot();
 2510
 2511                let language_servers: Vec<_> = self
 2512                    .language_servers_for_buffer(buffer, cx)
 2513                    .map(|i| i.1.clone())
 2514                    .collect();
 2515
 2516                for language_server in language_servers {
 2517                    let language_server = language_server.clone();
 2518
 2519                    let buffer_snapshots = self
 2520                        .buffer_snapshots
 2521                        .get_mut(&buffer.remote_id())
 2522                        .and_then(|m| m.get_mut(&language_server.server_id()))?;
 2523                    let previous_snapshot = buffer_snapshots.last()?;
 2524
 2525                    let build_incremental_change = || {
 2526                        buffer
 2527                            .edits_since::<(PointUtf16, usize)>(
 2528                                previous_snapshot.snapshot.version(),
 2529                            )
 2530                            .map(|edit| {
 2531                                let edit_start = edit.new.start.0;
 2532                                let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
 2533                                let new_text = next_snapshot
 2534                                    .text_for_range(edit.new.start.1..edit.new.end.1)
 2535                                    .collect();
 2536                                lsp::TextDocumentContentChangeEvent {
 2537                                    range: Some(lsp::Range::new(
 2538                                        point_to_lsp(edit_start),
 2539                                        point_to_lsp(edit_end),
 2540                                    )),
 2541                                    range_length: None,
 2542                                    text: new_text,
 2543                                }
 2544                            })
 2545                            .collect()
 2546                    };
 2547
 2548                    let document_sync_kind = language_server
 2549                        .capabilities()
 2550                        .text_document_sync
 2551                        .as_ref()
 2552                        .and_then(|sync| match sync {
 2553                            lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
 2554                            lsp::TextDocumentSyncCapability::Options(options) => options.change,
 2555                        });
 2556
 2557                    let content_changes: Vec<_> = match document_sync_kind {
 2558                        Some(lsp::TextDocumentSyncKind::FULL) => {
 2559                            vec![lsp::TextDocumentContentChangeEvent {
 2560                                range: None,
 2561                                range_length: None,
 2562                                text: next_snapshot.text(),
 2563                            }]
 2564                        }
 2565                        Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
 2566                        _ => {
 2567                            #[cfg(any(test, feature = "test-support"))]
 2568                            {
 2569                                build_incremental_change()
 2570                            }
 2571
 2572                            #[cfg(not(any(test, feature = "test-support")))]
 2573                            {
 2574                                continue;
 2575                            }
 2576                        }
 2577                    };
 2578
 2579                    let next_version = previous_snapshot.version + 1;
 2580
 2581                    buffer_snapshots.push(LspBufferSnapshot {
 2582                        version: next_version,
 2583                        snapshot: next_snapshot.clone(),
 2584                    });
 2585
 2586                    language_server
 2587                        .notify::<lsp::notification::DidChangeTextDocument>(
 2588                            lsp::DidChangeTextDocumentParams {
 2589                                text_document: lsp::VersionedTextDocumentIdentifier::new(
 2590                                    uri.clone(),
 2591                                    next_version,
 2592                                ),
 2593                                content_changes,
 2594                            },
 2595                        )
 2596                        .log_err();
 2597                }
 2598            }
 2599
 2600            BufferEvent::Saved => {
 2601                let file = File::from_dyn(buffer.read(cx).file())?;
 2602                let worktree_id = file.worktree_id(cx);
 2603                let abs_path = file.as_local()?.abs_path(cx);
 2604                let text_document = lsp::TextDocumentIdentifier {
 2605                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
 2606                };
 2607
 2608                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
 2609                    let text = include_text(server.as_ref()).then(|| buffer.read(cx).text());
 2610
 2611                    server
 2612                        .notify::<lsp::notification::DidSaveTextDocument>(
 2613                            lsp::DidSaveTextDocumentParams {
 2614                                text_document: text_document.clone(),
 2615                                text,
 2616                            },
 2617                        )
 2618                        .log_err();
 2619                }
 2620
 2621                let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
 2622                for language_server_id in language_server_ids {
 2623                    if let Some(LanguageServerState::Running {
 2624                        adapter,
 2625                        simulate_disk_based_diagnostics_completion,
 2626                        ..
 2627                    }) = self.language_servers.get_mut(&language_server_id)
 2628                    {
 2629                        // After saving a buffer using a language server that doesn't provide
 2630                        // a disk-based progress token, kick off a timer that will reset every
 2631                        // time the buffer is saved. If the timer eventually fires, simulate
 2632                        // disk-based diagnostics being finished so that other pieces of UI
 2633                        // (e.g., project diagnostics view, diagnostic status bar) can update.
 2634                        // We don't emit an event right away because the language server might take
 2635                        // some time to publish diagnostics.
 2636                        if adapter.disk_based_diagnostics_progress_token.is_none() {
 2637                            const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
 2638                                Duration::from_secs(1);
 2639
 2640                            let task = cx.spawn(move |this, mut cx| async move {
 2641                                cx.background_executor().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
 2642                                if let Some(this) = this.upgrade() {
 2643                                    this.update(&mut cx, |this, cx| {
 2644                                        this.disk_based_diagnostics_finished(
 2645                                            language_server_id,
 2646                                            cx,
 2647                                        );
 2648                                        this.enqueue_buffer_ordered_message(
 2649                                                BufferOrderedMessage::LanguageServerUpdate {
 2650                                                    language_server_id,
 2651                                                    message:proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(Default::default())
 2652                                                },
 2653                                            )
 2654                                            .ok();
 2655                                    }).ok();
 2656                                }
 2657                            });
 2658                            *simulate_disk_based_diagnostics_completion = Some(task);
 2659                        }
 2660                    }
 2661                }
 2662            }
 2663            BufferEvent::FileHandleChanged => {
 2664                let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
 2665                    return None;
 2666                };
 2667
 2668                let remote_id = buffer.read(cx).remote_id();
 2669                if let Some(entry_id) = file.entry_id {
 2670                    match self.local_buffer_ids_by_entry_id.get(&entry_id) {
 2671                        Some(_) => {
 2672                            return None;
 2673                        }
 2674                        None => {
 2675                            self.local_buffer_ids_by_entry_id
 2676                                .insert(entry_id, remote_id);
 2677                        }
 2678                    }
 2679                };
 2680                self.local_buffer_ids_by_path.insert(
 2681                    ProjectPath {
 2682                        worktree_id: file.worktree_id(cx),
 2683                        path: file.path.clone(),
 2684                    },
 2685                    remote_id,
 2686                );
 2687            }
 2688            _ => {}
 2689        }
 2690
 2691        None
 2692    }
 2693
 2694    fn request_buffer_diff_recalculation(
 2695        &mut self,
 2696        buffer: &Model<Buffer>,
 2697        cx: &mut ModelContext<Self>,
 2698    ) {
 2699        self.buffers_needing_diff.insert(buffer.downgrade());
 2700        let first_insertion = self.buffers_needing_diff.len() == 1;
 2701
 2702        let settings = ProjectSettings::get_global(cx);
 2703        let delay = if let Some(delay) = settings.git.gutter_debounce {
 2704            delay
 2705        } else {
 2706            if first_insertion {
 2707                let this = cx.weak_model();
 2708                cx.defer(move |cx| {
 2709                    if let Some(this) = this.upgrade() {
 2710                        this.update(cx, |this, cx| {
 2711                            this.recalculate_buffer_diffs(cx).detach();
 2712                        });
 2713                    }
 2714                });
 2715            }
 2716            return;
 2717        };
 2718
 2719        const MIN_DELAY: u64 = 50;
 2720        let delay = delay.max(MIN_DELAY);
 2721        let duration = Duration::from_millis(delay);
 2722
 2723        self.git_diff_debouncer
 2724            .fire_new(duration, cx, move |this, cx| {
 2725                this.recalculate_buffer_diffs(cx)
 2726            });
 2727    }
 2728
 2729    fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
 2730        let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
 2731        cx.spawn(move |this, mut cx| async move {
 2732            let tasks: Vec<_> = buffers
 2733                .iter()
 2734                .filter_map(|buffer| {
 2735                    let buffer = buffer.upgrade()?;
 2736                    buffer
 2737                        .update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx))
 2738                        .ok()
 2739                        .flatten()
 2740                })
 2741                .collect();
 2742
 2743            futures::future::join_all(tasks).await;
 2744
 2745            this.update(&mut cx, |this, cx| {
 2746                if !this.buffers_needing_diff.is_empty() {
 2747                    this.recalculate_buffer_diffs(cx).detach();
 2748                } else {
 2749                    // TODO: Would a `ModelContext<Project>.notify()` suffice here?
 2750                    for buffer in buffers {
 2751                        if let Some(buffer) = buffer.upgrade() {
 2752                            buffer.update(cx, |_, cx| cx.notify());
 2753                        }
 2754                    }
 2755                }
 2756            })
 2757            .ok();
 2758        })
 2759    }
 2760
 2761    fn language_servers_for_worktree(
 2762        &self,
 2763        worktree_id: WorktreeId,
 2764    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
 2765        self.language_server_ids
 2766            .iter()
 2767            .filter_map(move |((language_server_worktree_id, _), id)| {
 2768                if *language_server_worktree_id == worktree_id {
 2769                    if let Some(LanguageServerState::Running {
 2770                        adapter,
 2771                        language,
 2772                        server,
 2773                        ..
 2774                    }) = self.language_servers.get(id)
 2775                    {
 2776                        return Some((adapter, language, server));
 2777                    }
 2778                }
 2779                None
 2780            })
 2781    }
 2782
 2783    fn maintain_buffer_languages(
 2784        languages: Arc<LanguageRegistry>,
 2785        cx: &mut ModelContext<Project>,
 2786    ) -> Task<()> {
 2787        let mut subscription = languages.subscribe();
 2788        let mut prev_reload_count = languages.reload_count();
 2789        cx.spawn(move |project, mut cx| async move {
 2790            while let Some(()) = subscription.next().await {
 2791                if let Some(project) = project.upgrade() {
 2792                    // If the language registry has been reloaded, then remove and
 2793                    // re-assign the languages on all open buffers.
 2794                    let reload_count = languages.reload_count();
 2795                    if reload_count > prev_reload_count {
 2796                        prev_reload_count = reload_count;
 2797                        project
 2798                            .update(&mut cx, |this, cx| {
 2799                                let buffers = this
 2800                                    .opened_buffers
 2801                                    .values()
 2802                                    .filter_map(|b| b.upgrade())
 2803                                    .collect::<Vec<_>>();
 2804                                for buffer in buffers {
 2805                                    if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
 2806                                    {
 2807                                        this.unregister_buffer_from_language_servers(
 2808                                            &buffer, &f, cx,
 2809                                        );
 2810                                        buffer
 2811                                            .update(cx, |buffer, cx| buffer.set_language(None, cx));
 2812                                    }
 2813                                }
 2814                            })
 2815                            .ok();
 2816                    }
 2817
 2818                    project
 2819                        .update(&mut cx, |project, cx| {
 2820                            let mut plain_text_buffers = Vec::new();
 2821                            let mut buffers_with_unknown_injections = Vec::new();
 2822                            for buffer in project.opened_buffers.values() {
 2823                                if let Some(handle) = buffer.upgrade() {
 2824                                    let buffer = &handle.read(cx);
 2825                                    if buffer.language().is_none()
 2826                                        || buffer.language() == Some(&*language::PLAIN_TEXT)
 2827                                    {
 2828                                        plain_text_buffers.push(handle);
 2829                                    } else if buffer.contains_unknown_injections() {
 2830                                        buffers_with_unknown_injections.push(handle);
 2831                                    }
 2832                                }
 2833                            }
 2834
 2835                            for buffer in plain_text_buffers {
 2836                                project.detect_language_for_buffer(&buffer, cx);
 2837                                project.register_buffer_with_language_servers(&buffer, cx);
 2838                            }
 2839
 2840                            for buffer in buffers_with_unknown_injections {
 2841                                buffer.update(cx, |buffer, cx| buffer.reparse(cx));
 2842                            }
 2843                        })
 2844                        .ok();
 2845                }
 2846            }
 2847        })
 2848    }
 2849
 2850    fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<Result<()>> {
 2851        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
 2852        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
 2853
 2854        let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
 2855            *settings_changed_tx.borrow_mut() = ();
 2856        });
 2857
 2858        cx.spawn(move |this, mut cx| async move {
 2859            while let Some(()) = settings_changed_rx.next().await {
 2860                let servers = this.update(&mut cx, |this, cx| {
 2861                    this.language_server_ids
 2862                        .iter()
 2863                        .filter_map(|((worktree_id, _), server_id)| {
 2864                            let worktree = this.worktree_for_id(*worktree_id, cx)?;
 2865                            let state = this.language_servers.get(server_id)?;
 2866                            let delegate = ProjectLspAdapterDelegate::new(this, &worktree, cx);
 2867                            match state {
 2868                                LanguageServerState::Starting(_) => None,
 2869                                LanguageServerState::Running {
 2870                                    adapter, server, ..
 2871                                } => Some((
 2872                                    adapter.adapter.clone(),
 2873                                    server.clone(),
 2874                                    delegate as Arc<dyn LspAdapterDelegate>,
 2875                                )),
 2876                            }
 2877                        })
 2878                        .collect::<Vec<_>>()
 2879                })?;
 2880
 2881                for (adapter, server, delegate) in servers {
 2882                    let settings = adapter.workspace_configuration(&delegate, &mut cx).await?;
 2883
 2884                    server
 2885                        .notify::<lsp::notification::DidChangeConfiguration>(
 2886                            lsp::DidChangeConfigurationParams { settings },
 2887                        )
 2888                        .ok();
 2889                }
 2890            }
 2891
 2892            drop(settings_observation);
 2893            anyhow::Ok(())
 2894        })
 2895    }
 2896
 2897    fn detect_language_for_buffer(
 2898        &mut self,
 2899        buffer_handle: &Model<Buffer>,
 2900        cx: &mut ModelContext<Self>,
 2901    ) {
 2902        // If the buffer has a language, set it and start the language server if we haven't already.
 2903        let buffer = buffer_handle.read(cx);
 2904        let Some(file) = buffer.file() else {
 2905            return;
 2906        };
 2907        let content = buffer.as_rope();
 2908        let Some(new_language_result) = self
 2909            .languages
 2910            .language_for_file(file, Some(content), cx)
 2911            .now_or_never()
 2912        else {
 2913            return;
 2914        };
 2915
 2916        match new_language_result {
 2917            Err(e) => {
 2918                if e.is::<language::LanguageNotFound>() {
 2919                    cx.emit(Event::LanguageNotFound(buffer_handle.clone()))
 2920                }
 2921            }
 2922            Ok(new_language) => {
 2923                self.set_language_for_buffer(buffer_handle, new_language, cx);
 2924            }
 2925        };
 2926    }
 2927
 2928    pub fn set_language_for_buffer(
 2929        &mut self,
 2930        buffer: &Model<Buffer>,
 2931        new_language: Arc<Language>,
 2932        cx: &mut ModelContext<Self>,
 2933    ) {
 2934        buffer.update(cx, |buffer, cx| {
 2935            if buffer.language().map_or(true, |old_language| {
 2936                !Arc::ptr_eq(old_language, &new_language)
 2937            }) {
 2938                buffer.set_language(Some(new_language.clone()), cx);
 2939            }
 2940        });
 2941
 2942        let buffer_file = buffer.read(cx).file().cloned();
 2943        let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
 2944        let buffer_file = File::from_dyn(buffer_file.as_ref());
 2945        let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
 2946        if let Some(prettier_plugins) =
 2947            prettier_support::prettier_plugins_for_language(&new_language, &settings)
 2948        {
 2949            self.install_default_prettier(worktree, prettier_plugins.iter().cloned(), cx);
 2950        };
 2951        if let Some(file) = buffer_file {
 2952            let worktree = file.worktree.clone();
 2953            if worktree.read(cx).is_local() {
 2954                self.start_language_servers(&worktree, new_language, cx);
 2955            }
 2956        }
 2957    }
 2958
 2959    fn start_language_servers(
 2960        &mut self,
 2961        worktree: &Model<Worktree>,
 2962        language: Arc<Language>,
 2963        cx: &mut ModelContext<Self>,
 2964    ) {
 2965        let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
 2966        let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
 2967        if !settings.enable_language_server {
 2968            return;
 2969        }
 2970
 2971        for adapter in self.languages.clone().lsp_adapters(&language) {
 2972            self.start_language_server(worktree, adapter.clone(), language.clone(), cx);
 2973        }
 2974    }
 2975
 2976    fn start_language_server(
 2977        &mut self,
 2978        worktree_handle: &Model<Worktree>,
 2979        adapter: Arc<CachedLspAdapter>,
 2980        language: Arc<Language>,
 2981        cx: &mut ModelContext<Self>,
 2982    ) {
 2983        if adapter.reinstall_attempt_count.load(SeqCst) > MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
 2984            return;
 2985        }
 2986
 2987        let worktree = worktree_handle.read(cx);
 2988        let worktree_id = worktree.id();
 2989        let worktree_path = worktree.abs_path();
 2990        let key = (worktree_id, adapter.name.clone());
 2991        if self.language_server_ids.contains_key(&key) {
 2992            return;
 2993        }
 2994
 2995        let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
 2996        let lsp_adapter_delegate = ProjectLspAdapterDelegate::new(self, worktree_handle, cx);
 2997        let pending_server = match self.languages.create_pending_language_server(
 2998            stderr_capture.clone(),
 2999            language.clone(),
 3000            adapter.clone(),
 3001            Arc::clone(&worktree_path),
 3002            lsp_adapter_delegate.clone(),
 3003            cx,
 3004        ) {
 3005            Some(pending_server) => pending_server,
 3006            None => return,
 3007        };
 3008
 3009        let project_settings = ProjectSettings::get(
 3010            Some(SettingsLocation {
 3011                worktree_id: worktree_id.to_proto() as usize,
 3012                path: Path::new(""),
 3013            }),
 3014            cx,
 3015        );
 3016        let lsp = project_settings.lsp.get(&adapter.name.0);
 3017        let override_options = lsp.and_then(|s| s.initialization_options.clone());
 3018
 3019        let server_id = pending_server.server_id;
 3020        let container_dir = pending_server.container_dir.clone();
 3021        let state = LanguageServerState::Starting({
 3022            let adapter = adapter.clone();
 3023            let server_name = adapter.name.0.clone();
 3024            let language = language.clone();
 3025            let key = key.clone();
 3026
 3027            cx.spawn(move |this, mut cx| async move {
 3028                let result = Self::setup_and_insert_language_server(
 3029                    this.clone(),
 3030                    lsp_adapter_delegate,
 3031                    override_options,
 3032                    pending_server,
 3033                    adapter.clone(),
 3034                    language.clone(),
 3035                    server_id,
 3036                    key,
 3037                    &mut cx,
 3038                )
 3039                .await;
 3040
 3041                match result {
 3042                    Ok(server) => {
 3043                        stderr_capture.lock().take();
 3044                        server
 3045                    }
 3046
 3047                    Err(err) => {
 3048                        log::error!("failed to start language server {server_name:?}: {err}");
 3049                        log::error!("server stderr: {:?}", stderr_capture.lock().take());
 3050
 3051                        let this = this.upgrade()?;
 3052                        let container_dir = container_dir?;
 3053
 3054                        let attempt_count = adapter.reinstall_attempt_count.fetch_add(1, SeqCst);
 3055                        if attempt_count >= MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
 3056                            let max = MAX_SERVER_REINSTALL_ATTEMPT_COUNT;
 3057                            log::error!("Hit {max} reinstallation attempts for {server_name:?}");
 3058                            return None;
 3059                        }
 3060
 3061                        log::info!(
 3062                            "retrying installation of language server {server_name:?} in {}s",
 3063                            SERVER_REINSTALL_DEBOUNCE_TIMEOUT.as_secs()
 3064                        );
 3065                        cx.background_executor()
 3066                            .timer(SERVER_REINSTALL_DEBOUNCE_TIMEOUT)
 3067                            .await;
 3068
 3069                        let installation_test_binary = adapter
 3070                            .installation_test_binary(container_dir.to_path_buf())
 3071                            .await;
 3072
 3073                        this.update(&mut cx, |_, cx| {
 3074                            Self::check_errored_server(
 3075                                language,
 3076                                adapter,
 3077                                server_id,
 3078                                installation_test_binary,
 3079                                cx,
 3080                            )
 3081                        })
 3082                        .ok();
 3083
 3084                        None
 3085                    }
 3086                }
 3087            })
 3088        });
 3089
 3090        self.language_servers.insert(server_id, state);
 3091        self.language_server_ids.insert(key, server_id);
 3092    }
 3093
 3094    fn reinstall_language_server(
 3095        &mut self,
 3096        language: Arc<Language>,
 3097        adapter: Arc<CachedLspAdapter>,
 3098        server_id: LanguageServerId,
 3099        cx: &mut ModelContext<Self>,
 3100    ) -> Option<Task<()>> {
 3101        log::info!("beginning to reinstall server");
 3102
 3103        let existing_server = match self.language_servers.remove(&server_id) {
 3104            Some(LanguageServerState::Running { server, .. }) => Some(server),
 3105            _ => None,
 3106        };
 3107
 3108        for worktree in &self.worktrees {
 3109            if let Some(worktree) = worktree.upgrade() {
 3110                let key = (worktree.read(cx).id(), adapter.name.clone());
 3111                self.language_server_ids.remove(&key);
 3112            }
 3113        }
 3114
 3115        Some(cx.spawn(move |this, mut cx| async move {
 3116            if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
 3117                log::info!("shutting down existing server");
 3118                task.await;
 3119            }
 3120
 3121            // TODO: This is race-safe with regards to preventing new instances from
 3122            // starting while deleting, but existing instances in other projects are going
 3123            // to be very confused and messed up
 3124            let Some(task) = this
 3125                .update(&mut cx, |this, cx| {
 3126                    this.languages.delete_server_container(adapter.clone(), cx)
 3127                })
 3128                .log_err()
 3129            else {
 3130                return;
 3131            };
 3132            task.await;
 3133
 3134            this.update(&mut cx, |this, cx| {
 3135                let worktrees = this.worktrees.clone();
 3136                for worktree in worktrees {
 3137                    if let Some(worktree) = worktree.upgrade() {
 3138                        this.start_language_server(
 3139                            &worktree,
 3140                            adapter.clone(),
 3141                            language.clone(),
 3142                            cx,
 3143                        );
 3144                    }
 3145                }
 3146            })
 3147            .ok();
 3148        }))
 3149    }
 3150
 3151    #[allow(clippy::too_many_arguments)]
 3152    async fn setup_and_insert_language_server(
 3153        this: WeakModel<Self>,
 3154        delegate: Arc<dyn LspAdapterDelegate>,
 3155        override_initialization_options: Option<serde_json::Value>,
 3156        pending_server: PendingLanguageServer,
 3157        adapter: Arc<CachedLspAdapter>,
 3158        language: Arc<Language>,
 3159        server_id: LanguageServerId,
 3160        key: (WorktreeId, LanguageServerName),
 3161        cx: &mut AsyncAppContext,
 3162    ) -> Result<Option<Arc<LanguageServer>>> {
 3163        let language_server = Self::setup_pending_language_server(
 3164            this.clone(),
 3165            override_initialization_options,
 3166            pending_server,
 3167            delegate,
 3168            adapter.clone(),
 3169            server_id,
 3170            cx,
 3171        )
 3172        .await?;
 3173
 3174        let this = match this.upgrade() {
 3175            Some(this) => this,
 3176            None => return Err(anyhow!("failed to upgrade project handle")),
 3177        };
 3178
 3179        this.update(cx, |this, cx| {
 3180            this.insert_newly_running_language_server(
 3181                language,
 3182                adapter,
 3183                language_server.clone(),
 3184                server_id,
 3185                key,
 3186                cx,
 3187            )
 3188        })??;
 3189
 3190        Ok(Some(language_server))
 3191    }
 3192
 3193    async fn setup_pending_language_server(
 3194        this: WeakModel<Self>,
 3195        override_options: Option<serde_json::Value>,
 3196        pending_server: PendingLanguageServer,
 3197        delegate: Arc<dyn LspAdapterDelegate>,
 3198        adapter: Arc<CachedLspAdapter>,
 3199        server_id: LanguageServerId,
 3200        cx: &mut AsyncAppContext,
 3201    ) -> Result<Arc<LanguageServer>> {
 3202        let workspace_config = adapter
 3203            .adapter
 3204            .clone()
 3205            .workspace_configuration(&delegate, cx)
 3206            .await?;
 3207        let (language_server, mut initialization_options) = pending_server.task.await?;
 3208
 3209        let name = language_server.name();
 3210        language_server
 3211            .on_notification::<lsp::notification::PublishDiagnostics, _>({
 3212                let adapter = adapter.clone();
 3213                let this = this.clone();
 3214                move |mut params, mut cx| {
 3215                    let adapter = adapter.clone();
 3216                    if let Some(this) = this.upgrade() {
 3217                        adapter.process_diagnostics(&mut params);
 3218                        this.update(&mut cx, |this, cx| {
 3219                            this.update_diagnostics(
 3220                                server_id,
 3221                                params,
 3222                                &adapter.disk_based_diagnostic_sources,
 3223                                cx,
 3224                            )
 3225                            .log_err();
 3226                        })
 3227                        .ok();
 3228                    }
 3229                }
 3230            })
 3231            .detach();
 3232
 3233        language_server
 3234            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
 3235                let adapter = adapter.adapter.clone();
 3236                let delegate = delegate.clone();
 3237                move |params, mut cx| {
 3238                    let adapter = adapter.clone();
 3239                    let delegate = delegate.clone();
 3240                    async move {
 3241                        let workspace_config =
 3242                            adapter.workspace_configuration(&delegate, &mut cx).await?;
 3243                        Ok(params
 3244                            .items
 3245                            .into_iter()
 3246                            .map(|item| {
 3247                                if let Some(section) = &item.section {
 3248                                    workspace_config
 3249                                        .get(section)
 3250                                        .cloned()
 3251                                        .unwrap_or(serde_json::Value::Null)
 3252                                } else {
 3253                                    workspace_config.clone()
 3254                                }
 3255                            })
 3256                            .collect())
 3257                    }
 3258                }
 3259            })
 3260            .detach();
 3261
 3262        // Even though we don't have handling for these requests, respond to them to
 3263        // avoid stalling any language server like `gopls` which waits for a response
 3264        // to these requests when initializing.
 3265        language_server
 3266            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
 3267                let this = this.clone();
 3268                move |params, mut cx| {
 3269                    let this = this.clone();
 3270                    async move {
 3271                        this.update(&mut cx, |this, _| {
 3272                            if let Some(status) = this.language_server_statuses.get_mut(&server_id)
 3273                            {
 3274                                if let lsp::NumberOrString::String(token) = params.token {
 3275                                    status.progress_tokens.insert(token);
 3276                                }
 3277                            }
 3278                        })?;
 3279
 3280                        Ok(())
 3281                    }
 3282                }
 3283            })
 3284            .detach();
 3285
 3286        language_server
 3287            .on_request::<lsp::request::RegisterCapability, _, _>({
 3288                let this = this.clone();
 3289                move |params, mut cx| {
 3290                    let this = this.clone();
 3291                    async move {
 3292                        for reg in params.registrations {
 3293                            if reg.method == "workspace/didChangeWatchedFiles" {
 3294                                if let Some(options) = reg.register_options {
 3295                                    let options = serde_json::from_value(options)?;
 3296                                    this.update(&mut cx, |this, cx| {
 3297                                        this.on_lsp_did_change_watched_files(
 3298                                            server_id, options, cx,
 3299                                        );
 3300                                    })?;
 3301                                }
 3302                            }
 3303                        }
 3304                        Ok(())
 3305                    }
 3306                }
 3307            })
 3308            .detach();
 3309
 3310        language_server
 3311            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
 3312                let adapter = adapter.clone();
 3313                let this = this.clone();
 3314                move |params, cx| {
 3315                    Self::on_lsp_workspace_edit(
 3316                        this.clone(),
 3317                        params,
 3318                        server_id,
 3319                        adapter.clone(),
 3320                        cx,
 3321                    )
 3322                }
 3323            })
 3324            .detach();
 3325
 3326        language_server
 3327            .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
 3328                let this = this.clone();
 3329                move |(), mut cx| {
 3330                    let this = this.clone();
 3331                    async move {
 3332                        this.update(&mut cx, |project, cx| {
 3333                            cx.emit(Event::RefreshInlayHints);
 3334                            project.remote_id().map(|project_id| {
 3335                                project.client.send(proto::RefreshInlayHints { project_id })
 3336                            })
 3337                        })?
 3338                        .transpose()?;
 3339                        Ok(())
 3340                    }
 3341                }
 3342            })
 3343            .detach();
 3344
 3345        language_server
 3346            .on_request::<lsp::request::ShowMessageRequest, _, _>({
 3347                let this = this.clone();
 3348                let name = name.to_string();
 3349                move |params, mut cx| {
 3350                    let this = this.clone();
 3351                    let name = name.to_string();
 3352                    async move {
 3353                        if let Some(actions) = params.actions {
 3354                            let (tx, mut rx) = smol::channel::bounded(1);
 3355                            let request = LanguageServerPromptRequest {
 3356                                level: match params.typ {
 3357                                    lsp::MessageType::ERROR => PromptLevel::Critical,
 3358                                    lsp::MessageType::WARNING => PromptLevel::Warning,
 3359                                    _ => PromptLevel::Info,
 3360                                },
 3361                                message: params.message,
 3362                                actions,
 3363                                response_channel: tx,
 3364                                lsp_name: name.clone(),
 3365                            };
 3366
 3367                            if let Ok(_) = this.update(&mut cx, |_, cx| {
 3368                                cx.emit(Event::LanguageServerPrompt(request));
 3369                            }) {
 3370                                let response = rx.next().await;
 3371
 3372                                Ok(response)
 3373                            } else {
 3374                                Ok(None)
 3375                            }
 3376                        } else {
 3377                            Ok(None)
 3378                        }
 3379                    }
 3380                }
 3381            })
 3382            .detach();
 3383
 3384        let disk_based_diagnostics_progress_token =
 3385            adapter.disk_based_diagnostics_progress_token.clone();
 3386
 3387        language_server
 3388            .on_notification::<ServerStatus, _>({
 3389                let this = this.clone();
 3390                let name = name.to_string();
 3391                move |params, mut cx| {
 3392                    let this = this.clone();
 3393                    let name = name.to_string();
 3394                    if let Some(ref message) = params.message {
 3395                        let message = message.trim();
 3396                        if !message.is_empty() {
 3397                            let formatted_message = format!(
 3398                                "Language server {name} (id {server_id}) status update: {message}"
 3399                            );
 3400                            match params.health {
 3401                                ServerHealthStatus::Ok => log::info!("{}", formatted_message),
 3402                                ServerHealthStatus::Warning => log::warn!("{}", formatted_message),
 3403                                ServerHealthStatus::Error => {
 3404                                    log::error!("{}", formatted_message);
 3405                                    let (tx, _rx) = smol::channel::bounded(1);
 3406                                    let request = LanguageServerPromptRequest {
 3407                                        level: PromptLevel::Critical,
 3408                                        message: params.message.unwrap_or_default(),
 3409                                        actions: Vec::new(),
 3410                                        response_channel: tx,
 3411                                        lsp_name: name.clone(),
 3412                                    };
 3413                                    let _ = this
 3414                                        .update(&mut cx, |_, cx| {
 3415                                            cx.emit(Event::LanguageServerPrompt(request));
 3416                                        })
 3417                                        .ok();
 3418                                }
 3419                                ServerHealthStatus::Other(status) => {
 3420                                    log::info!(
 3421                                        "Unknown server health: {status}\n{formatted_message}"
 3422                                    )
 3423                                }
 3424                            }
 3425                        }
 3426                    }
 3427                }
 3428            })
 3429            .detach();
 3430
 3431        language_server
 3432            .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
 3433                if let Some(this) = this.upgrade() {
 3434                    this.update(&mut cx, |this, cx| {
 3435                        this.on_lsp_progress(
 3436                            params,
 3437                            server_id,
 3438                            disk_based_diagnostics_progress_token.clone(),
 3439                            cx,
 3440                        );
 3441                    })
 3442                    .ok();
 3443                }
 3444            })
 3445            .detach();
 3446
 3447        match (&mut initialization_options, override_options) {
 3448            (Some(initialization_options), Some(override_options)) => {
 3449                merge_json_value_into(override_options, initialization_options);
 3450            }
 3451            (None, override_options) => initialization_options = override_options,
 3452            _ => {}
 3453        }
 3454        let language_server = cx
 3455            .update(|cx| language_server.initialize(initialization_options, cx))?
 3456            .await?;
 3457
 3458        language_server
 3459            .notify::<lsp::notification::DidChangeConfiguration>(
 3460                lsp::DidChangeConfigurationParams {
 3461                    settings: workspace_config,
 3462                },
 3463            )
 3464            .ok();
 3465
 3466        Ok(language_server)
 3467    }
 3468
 3469    fn insert_newly_running_language_server(
 3470        &mut self,
 3471        language: Arc<Language>,
 3472        adapter: Arc<CachedLspAdapter>,
 3473        language_server: Arc<LanguageServer>,
 3474        server_id: LanguageServerId,
 3475        key: (WorktreeId, LanguageServerName),
 3476        cx: &mut ModelContext<Self>,
 3477    ) -> Result<()> {
 3478        // If the language server for this key doesn't match the server id, don't store the
 3479        // server. Which will cause it to be dropped, killing the process
 3480        if self
 3481            .language_server_ids
 3482            .get(&key)
 3483            .map(|id| id != &server_id)
 3484            .unwrap_or(false)
 3485        {
 3486            return Ok(());
 3487        }
 3488
 3489        // Update language_servers collection with Running variant of LanguageServerState
 3490        // indicating that the server is up and running and ready
 3491        self.language_servers.insert(
 3492            server_id,
 3493            LanguageServerState::Running {
 3494                adapter: adapter.clone(),
 3495                language: language.clone(),
 3496                server: language_server.clone(),
 3497                simulate_disk_based_diagnostics_completion: None,
 3498            },
 3499        );
 3500
 3501        self.language_server_statuses.insert(
 3502            server_id,
 3503            LanguageServerStatus {
 3504                name: language_server.name().to_string(),
 3505                pending_work: Default::default(),
 3506                has_pending_diagnostic_updates: false,
 3507                progress_tokens: Default::default(),
 3508            },
 3509        );
 3510
 3511        cx.emit(Event::LanguageServerAdded(server_id));
 3512
 3513        if let Some(project_id) = self.remote_id() {
 3514            self.client.send(proto::StartLanguageServer {
 3515                project_id,
 3516                server: Some(proto::LanguageServer {
 3517                    id: server_id.0 as u64,
 3518                    name: language_server.name().to_string(),
 3519                }),
 3520            })?;
 3521        }
 3522
 3523        // Tell the language server about every open buffer in the worktree that matches the language.
 3524        for buffer in self.opened_buffers.values() {
 3525            if let Some(buffer_handle) = buffer.upgrade() {
 3526                let buffer = buffer_handle.read(cx);
 3527                let file = match File::from_dyn(buffer.file()) {
 3528                    Some(file) => file,
 3529                    None => continue,
 3530                };
 3531                let language = match buffer.language() {
 3532                    Some(language) => language,
 3533                    None => continue,
 3534                };
 3535
 3536                if file.worktree.read(cx).id() != key.0
 3537                    || !self
 3538                        .languages
 3539                        .lsp_adapters(&language)
 3540                        .iter()
 3541                        .any(|a| a.name == key.1)
 3542                {
 3543                    continue;
 3544                }
 3545
 3546                let file = match file.as_local() {
 3547                    Some(file) => file,
 3548                    None => continue,
 3549                };
 3550
 3551                let versions = self
 3552                    .buffer_snapshots
 3553                    .entry(buffer.remote_id())
 3554                    .or_default()
 3555                    .entry(server_id)
 3556                    .or_insert_with(|| {
 3557                        vec![LspBufferSnapshot {
 3558                            version: 0,
 3559                            snapshot: buffer.text_snapshot(),
 3560                        }]
 3561                    });
 3562
 3563                let snapshot = versions.last().unwrap();
 3564                let version = snapshot.version;
 3565                let initial_snapshot = &snapshot.snapshot;
 3566                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
 3567                language_server.notify::<lsp::notification::DidOpenTextDocument>(
 3568                    lsp::DidOpenTextDocumentParams {
 3569                        text_document: lsp::TextDocumentItem::new(
 3570                            uri,
 3571                            adapter
 3572                                .language_ids
 3573                                .get(language.name().as_ref())
 3574                                .cloned()
 3575                                .unwrap_or_default(),
 3576                            version,
 3577                            initial_snapshot.text(),
 3578                        ),
 3579                    },
 3580                )?;
 3581
 3582                buffer_handle.update(cx, |buffer, cx| {
 3583                    buffer.set_completion_triggers(
 3584                        language_server
 3585                            .capabilities()
 3586                            .completion_provider
 3587                            .as_ref()
 3588                            .and_then(|provider| provider.trigger_characters.clone())
 3589                            .unwrap_or_default(),
 3590                        cx,
 3591                    )
 3592                });
 3593            }
 3594        }
 3595
 3596        cx.notify();
 3597        Ok(())
 3598    }
 3599
 3600    // Returns a list of all of the worktrees which no longer have a language server and the root path
 3601    // for the stopped server
 3602    fn stop_language_server(
 3603        &mut self,
 3604        worktree_id: WorktreeId,
 3605        adapter_name: LanguageServerName,
 3606        cx: &mut ModelContext<Self>,
 3607    ) -> Task<Vec<WorktreeId>> {
 3608        let key = (worktree_id, adapter_name);
 3609        if let Some(server_id) = self.language_server_ids.remove(&key) {
 3610            let name = key.1 .0;
 3611            log::info!("stopping language server {name}");
 3612
 3613            // Remove other entries for this language server as well
 3614            let mut orphaned_worktrees = vec![worktree_id];
 3615            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
 3616            for other_key in other_keys {
 3617                if self.language_server_ids.get(&other_key) == Some(&server_id) {
 3618                    self.language_server_ids.remove(&other_key);
 3619                    orphaned_worktrees.push(other_key.0);
 3620                }
 3621            }
 3622
 3623            for buffer in self.opened_buffers.values() {
 3624                if let Some(buffer) = buffer.upgrade() {
 3625                    buffer.update(cx, |buffer, cx| {
 3626                        buffer.update_diagnostics(server_id, Default::default(), cx);
 3627                    });
 3628                }
 3629            }
 3630            for worktree in &self.worktrees {
 3631                if let Some(worktree) = worktree.upgrade() {
 3632                    worktree.update(cx, |worktree, cx| {
 3633                        if let Some(worktree) = worktree.as_local_mut() {
 3634                            worktree.clear_diagnostics_for_language_server(server_id, cx);
 3635                        }
 3636                    });
 3637                }
 3638            }
 3639
 3640            self.language_server_watched_paths.remove(&server_id);
 3641            self.language_server_statuses.remove(&server_id);
 3642            cx.notify();
 3643
 3644            let server_state = self.language_servers.remove(&server_id);
 3645            cx.emit(Event::LanguageServerRemoved(server_id));
 3646            cx.spawn(move |_, cx| async move {
 3647                Self::shutdown_language_server(server_state, name, cx).await;
 3648                orphaned_worktrees
 3649            })
 3650        } else {
 3651            Task::ready(Vec::new())
 3652        }
 3653    }
 3654
 3655    async fn shutdown_language_server(
 3656        server_state: Option<LanguageServerState>,
 3657        name: Arc<str>,
 3658        cx: AsyncAppContext,
 3659    ) {
 3660        let server = match server_state {
 3661            Some(LanguageServerState::Starting(task)) => {
 3662                let mut timer = cx
 3663                    .background_executor()
 3664                    .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
 3665                    .fuse();
 3666
 3667                select! {
 3668                    server = task.fuse() => server,
 3669                    _ = timer => {
 3670                        log::info!(
 3671                            "timeout waiting for language server {} to finish launching before stopping",
 3672                            name
 3673                        );
 3674                        None
 3675                    },
 3676                }
 3677            }
 3678
 3679            Some(LanguageServerState::Running { server, .. }) => Some(server),
 3680
 3681            None => None,
 3682        };
 3683
 3684        if let Some(server) = server {
 3685            if let Some(shutdown) = server.shutdown() {
 3686                shutdown.await;
 3687            }
 3688        }
 3689    }
 3690
 3691    pub fn restart_language_servers_for_buffers(
 3692        &mut self,
 3693        buffers: impl IntoIterator<Item = Model<Buffer>>,
 3694        cx: &mut ModelContext<Self>,
 3695    ) -> Option<()> {
 3696        let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
 3697            .into_iter()
 3698            .filter_map(|buffer| {
 3699                let buffer = buffer.read(cx);
 3700                let file = buffer.file()?;
 3701                let worktree = File::from_dyn(Some(file))?.worktree.clone();
 3702                let language = self
 3703                    .languages
 3704                    .language_for_file(file, Some(buffer.as_rope()), cx)
 3705                    .now_or_never()?
 3706                    .ok()?;
 3707                Some((worktree, language))
 3708            })
 3709            .collect();
 3710        for (worktree, language) in language_server_lookup_info {
 3711            self.restart_language_servers(worktree, language, cx);
 3712        }
 3713
 3714        None
 3715    }
 3716
 3717    fn restart_language_servers(
 3718        &mut self,
 3719        worktree: Model<Worktree>,
 3720        language: Arc<Language>,
 3721        cx: &mut ModelContext<Self>,
 3722    ) {
 3723        let worktree_id = worktree.read(cx).id();
 3724
 3725        let stop_tasks = self
 3726            .languages
 3727            .clone()
 3728            .lsp_adapters(&language)
 3729            .iter()
 3730            .map(|adapter| {
 3731                let stop_task = self.stop_language_server(worktree_id, adapter.name.clone(), cx);
 3732                (stop_task, adapter.name.clone())
 3733            })
 3734            .collect::<Vec<_>>();
 3735        if stop_tasks.is_empty() {
 3736            return;
 3737        }
 3738
 3739        cx.spawn(move |this, mut cx| async move {
 3740            // For each stopped language server, record all of the worktrees with which
 3741            // it was associated.
 3742            let mut affected_worktrees = Vec::new();
 3743            for (stop_task, language_server_name) in stop_tasks {
 3744                for affected_worktree_id in stop_task.await {
 3745                    affected_worktrees.push((affected_worktree_id, language_server_name.clone()));
 3746                }
 3747            }
 3748
 3749            this.update(&mut cx, |this, cx| {
 3750                // Restart the language server for the given worktree.
 3751                this.start_language_servers(&worktree, language.clone(), cx);
 3752
 3753                // Lookup new server ids and set them for each of the orphaned worktrees
 3754                for (affected_worktree_id, language_server_name) in affected_worktrees {
 3755                    if let Some(new_server_id) = this
 3756                        .language_server_ids
 3757                        .get(&(worktree_id, language_server_name.clone()))
 3758                        .cloned()
 3759                    {
 3760                        this.language_server_ids
 3761                            .insert((affected_worktree_id, language_server_name), new_server_id);
 3762                    }
 3763                }
 3764            })
 3765            .ok();
 3766        })
 3767        .detach();
 3768    }
 3769
 3770    fn check_errored_server(
 3771        language: Arc<Language>,
 3772        adapter: Arc<CachedLspAdapter>,
 3773        server_id: LanguageServerId,
 3774        installation_test_binary: Option<LanguageServerBinary>,
 3775        cx: &mut ModelContext<Self>,
 3776    ) {
 3777        if !adapter.can_be_reinstalled() {
 3778            log::info!(
 3779                "Validation check requested for {:?} but it cannot be reinstalled",
 3780                adapter.name.0
 3781            );
 3782            return;
 3783        }
 3784
 3785        cx.spawn(move |this, mut cx| async move {
 3786            log::info!("About to spawn test binary");
 3787
 3788            // A lack of test binary counts as a failure
 3789            let process = installation_test_binary.and_then(|binary| {
 3790                smol::process::Command::new(&binary.path)
 3791                    .current_dir(&binary.path)
 3792                    .args(binary.arguments)
 3793                    .stdin(Stdio::piped())
 3794                    .stdout(Stdio::piped())
 3795                    .stderr(Stdio::inherit())
 3796                    .kill_on_drop(true)
 3797                    .spawn()
 3798                    .ok()
 3799            });
 3800
 3801            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
 3802            let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
 3803
 3804            let mut errored = false;
 3805            if let Some(mut process) = process {
 3806                futures::select! {
 3807                    status = process.status().fuse() => match status {
 3808                        Ok(status) => errored = !status.success(),
 3809                        Err(_) => errored = true,
 3810                    },
 3811
 3812                    _ = timeout => {
 3813                        log::info!("test binary time-ed out, this counts as a success");
 3814                        _ = process.kill();
 3815                    }
 3816                }
 3817            } else {
 3818                log::warn!("test binary failed to launch");
 3819                errored = true;
 3820            }
 3821
 3822            if errored {
 3823                log::warn!("test binary check failed");
 3824                let task = this
 3825                    .update(&mut cx, move |this, cx| {
 3826                        this.reinstall_language_server(language, adapter, server_id, cx)
 3827                    })
 3828                    .ok()
 3829                    .flatten();
 3830
 3831                if let Some(task) = task {
 3832                    task.await;
 3833                }
 3834            }
 3835        })
 3836        .detach();
 3837    }
 3838
 3839    fn enqueue_language_server_progress(
 3840        &mut self,
 3841        message: BufferOrderedMessage,
 3842        cx: &mut ModelContext<Self>,
 3843    ) {
 3844        self.pending_language_server_update.replace(message);
 3845        self.flush_language_server_update.get_or_insert_with(|| {
 3846            cx.spawn(|this, mut cx| async move {
 3847                cx.background_executor()
 3848                    .timer(SERVER_PROGRESS_DEBOUNCE_TIMEOUT)
 3849                    .await;
 3850                this.update(&mut cx, |this, _| {
 3851                    this.flush_language_server_update.take();
 3852                    if let Some(update) = this.pending_language_server_update.take() {
 3853                        this.enqueue_buffer_ordered_message(update).ok();
 3854                    }
 3855                })
 3856                .ok();
 3857            })
 3858        });
 3859    }
 3860
 3861    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
 3862        if let Some(pending_message) = self.pending_language_server_update.take() {
 3863            self.flush_language_server_update.take();
 3864            self.buffer_ordered_messages_tx
 3865                .unbounded_send(pending_message)
 3866                .map_err(|e| anyhow!(e))?;
 3867        }
 3868        self.buffer_ordered_messages_tx
 3869            .unbounded_send(message)
 3870            .map_err(|e| anyhow!(e))
 3871    }
 3872
 3873    fn on_lsp_progress(
 3874        &mut self,
 3875        progress: lsp::ProgressParams,
 3876        language_server_id: LanguageServerId,
 3877        disk_based_diagnostics_progress_token: Option<String>,
 3878        cx: &mut ModelContext<Self>,
 3879    ) {
 3880        let token = match progress.token {
 3881            lsp::NumberOrString::String(token) => token,
 3882            lsp::NumberOrString::Number(token) => {
 3883                log::info!("skipping numeric progress token {}", token);
 3884                return;
 3885            }
 3886        };
 3887        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
 3888        let language_server_status =
 3889            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 3890                status
 3891            } else {
 3892                return;
 3893            };
 3894
 3895        if !language_server_status.progress_tokens.contains(&token) {
 3896            return;
 3897        }
 3898
 3899        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
 3900            .as_ref()
 3901            .map_or(false, |disk_based_token| {
 3902                token.starts_with(disk_based_token)
 3903            });
 3904
 3905        match progress {
 3906            lsp::WorkDoneProgress::Begin(report) => {
 3907                if is_disk_based_diagnostics_progress {
 3908                    language_server_status.has_pending_diagnostic_updates = true;
 3909                    self.disk_based_diagnostics_started(language_server_id, cx);
 3910                    self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 3911                            language_server_id,
 3912                            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
 3913                        })
 3914                        .ok();
 3915                } else {
 3916                    self.on_lsp_work_start(
 3917                        language_server_id,
 3918                        token.clone(),
 3919                        LanguageServerProgress {
 3920                            message: report.message.clone(),
 3921                            percentage: report.percentage.map(|p| p as usize),
 3922                            last_update_at: Instant::now(),
 3923                        },
 3924                        cx,
 3925                    );
 3926                    self.enqueue_buffer_ordered_message(
 3927                        BufferOrderedMessage::LanguageServerUpdate {
 3928                            language_server_id,
 3929                            message: proto::update_language_server::Variant::WorkStart(
 3930                                proto::LspWorkStart {
 3931                                    token,
 3932                                    message: report.message,
 3933                                    percentage: report.percentage,
 3934                                },
 3935                            ),
 3936                        },
 3937                    )
 3938                    .ok();
 3939                }
 3940            }
 3941            lsp::WorkDoneProgress::Report(report) => {
 3942                if !is_disk_based_diagnostics_progress {
 3943                    self.on_lsp_work_progress(
 3944                        language_server_id,
 3945                        token.clone(),
 3946                        LanguageServerProgress {
 3947                            message: report.message.clone(),
 3948                            percentage: report.percentage.map(|p| p as usize),
 3949                            last_update_at: Instant::now(),
 3950                        },
 3951                        cx,
 3952                    );
 3953                    self.enqueue_language_server_progress(
 3954                        BufferOrderedMessage::LanguageServerUpdate {
 3955                            language_server_id,
 3956                            message: proto::update_language_server::Variant::WorkProgress(
 3957                                proto::LspWorkProgress {
 3958                                    token,
 3959                                    message: report.message,
 3960                                    percentage: report.percentage,
 3961                                },
 3962                            ),
 3963                        },
 3964                        cx,
 3965                    );
 3966                }
 3967            }
 3968            lsp::WorkDoneProgress::End(_) => {
 3969                language_server_status.progress_tokens.remove(&token);
 3970
 3971                if is_disk_based_diagnostics_progress {
 3972                    language_server_status.has_pending_diagnostic_updates = false;
 3973                    self.disk_based_diagnostics_finished(language_server_id, cx);
 3974                    self.enqueue_buffer_ordered_message(
 3975                        BufferOrderedMessage::LanguageServerUpdate {
 3976                            language_server_id,
 3977                            message:
 3978                                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
 3979                                    Default::default(),
 3980                                ),
 3981                        },
 3982                    )
 3983                    .ok();
 3984                } else {
 3985                    self.on_lsp_work_end(language_server_id, token.clone(), cx);
 3986                    self.enqueue_buffer_ordered_message(
 3987                        BufferOrderedMessage::LanguageServerUpdate {
 3988                            language_server_id,
 3989                            message: proto::update_language_server::Variant::WorkEnd(
 3990                                proto::LspWorkEnd { token },
 3991                            ),
 3992                        },
 3993                    )
 3994                    .ok();
 3995                }
 3996            }
 3997        }
 3998    }
 3999
 4000    fn on_lsp_work_start(
 4001        &mut self,
 4002        language_server_id: LanguageServerId,
 4003        token: String,
 4004        progress: LanguageServerProgress,
 4005        cx: &mut ModelContext<Self>,
 4006    ) {
 4007        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4008            status.pending_work.insert(token, progress);
 4009            cx.notify();
 4010        }
 4011    }
 4012
 4013    fn on_lsp_work_progress(
 4014        &mut self,
 4015        language_server_id: LanguageServerId,
 4016        token: String,
 4017        progress: LanguageServerProgress,
 4018        cx: &mut ModelContext<Self>,
 4019    ) {
 4020        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4021            let entry = status
 4022                .pending_work
 4023                .entry(token)
 4024                .or_insert(LanguageServerProgress {
 4025                    message: Default::default(),
 4026                    percentage: Default::default(),
 4027                    last_update_at: progress.last_update_at,
 4028                });
 4029            if progress.message.is_some() {
 4030                entry.message = progress.message;
 4031            }
 4032            if progress.percentage.is_some() {
 4033                entry.percentage = progress.percentage;
 4034            }
 4035            entry.last_update_at = progress.last_update_at;
 4036            cx.notify();
 4037        }
 4038    }
 4039
 4040    fn on_lsp_work_end(
 4041        &mut self,
 4042        language_server_id: LanguageServerId,
 4043        token: String,
 4044        cx: &mut ModelContext<Self>,
 4045    ) {
 4046        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
 4047            cx.emit(Event::RefreshInlayHints);
 4048            status.pending_work.remove(&token);
 4049            cx.notify();
 4050        }
 4051    }
 4052
 4053    fn on_lsp_did_change_watched_files(
 4054        &mut self,
 4055        language_server_id: LanguageServerId,
 4056        params: DidChangeWatchedFilesRegistrationOptions,
 4057        cx: &mut ModelContext<Self>,
 4058    ) {
 4059        let watched_paths = self
 4060            .language_server_watched_paths
 4061            .entry(language_server_id)
 4062            .or_default();
 4063
 4064        let mut builders = HashMap::default();
 4065        for watcher in params.watchers {
 4066            for worktree in &self.worktrees {
 4067                if let Some(worktree) = worktree.upgrade() {
 4068                    let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
 4069                        if let Some(abs_path) = tree.abs_path().to_str() {
 4070                            let relative_glob_pattern = match &watcher.glob_pattern {
 4071                                lsp::GlobPattern::String(s) => Some(
 4072                                    s.strip_prefix(abs_path)
 4073                                        .unwrap_or(s)
 4074                                        .strip_prefix(std::path::MAIN_SEPARATOR)
 4075                                        .unwrap_or(s),
 4076                                ),
 4077                                lsp::GlobPattern::Relative(rp) => {
 4078                                    let base_uri = match &rp.base_uri {
 4079                                        lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
 4080                                        lsp::OneOf::Right(base_uri) => base_uri,
 4081                                    };
 4082                                    base_uri.to_file_path().ok().and_then(|file_path| {
 4083                                        (file_path.to_str() == Some(abs_path))
 4084                                            .then_some(rp.pattern.as_str())
 4085                                    })
 4086                                }
 4087                            };
 4088                            if let Some(relative_glob_pattern) = relative_glob_pattern {
 4089                                let literal_prefix = glob_literal_prefix(relative_glob_pattern);
 4090                                tree.as_local_mut()
 4091                                    .unwrap()
 4092                                    .add_path_prefix_to_scan(Path::new(literal_prefix).into());
 4093                                if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
 4094                                    builders
 4095                                        .entry(tree.id())
 4096                                        .or_insert_with(|| GlobSetBuilder::new())
 4097                                        .add(glob);
 4098                                }
 4099                                return true;
 4100                            }
 4101                        }
 4102                        false
 4103                    });
 4104                    if glob_is_inside_worktree {
 4105                        break;
 4106                    }
 4107                }
 4108            }
 4109        }
 4110
 4111        watched_paths.clear();
 4112        for (worktree_id, builder) in builders {
 4113            if let Ok(globset) = builder.build() {
 4114                watched_paths.insert(worktree_id, globset);
 4115            }
 4116        }
 4117
 4118        cx.notify();
 4119    }
 4120
 4121    async fn on_lsp_workspace_edit(
 4122        this: WeakModel<Self>,
 4123        params: lsp::ApplyWorkspaceEditParams,
 4124        server_id: LanguageServerId,
 4125        adapter: Arc<CachedLspAdapter>,
 4126        mut cx: AsyncAppContext,
 4127    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
 4128        let this = this
 4129            .upgrade()
 4130            .ok_or_else(|| anyhow!("project project closed"))?;
 4131        let language_server = this
 4132            .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
 4133            .ok_or_else(|| anyhow!("language server not found"))?;
 4134        let transaction = Self::deserialize_workspace_edit(
 4135            this.clone(),
 4136            params.edit,
 4137            true,
 4138            adapter.clone(),
 4139            language_server.clone(),
 4140            &mut cx,
 4141        )
 4142        .await
 4143        .log_err();
 4144        this.update(&mut cx, |this, _| {
 4145            if let Some(transaction) = transaction {
 4146                this.last_workspace_edits_by_language_server
 4147                    .insert(server_id, transaction);
 4148            }
 4149        })?;
 4150        Ok(lsp::ApplyWorkspaceEditResponse {
 4151            applied: true,
 4152            failed_change: None,
 4153            failure_reason: None,
 4154        })
 4155    }
 4156
 4157    pub fn language_server_statuses(
 4158        &self,
 4159    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
 4160        self.language_server_statuses.values()
 4161    }
 4162
 4163    pub fn last_formatting_failure(&self) -> Option<&str> {
 4164        self.last_formatting_failure.as_deref()
 4165    }
 4166
 4167    pub fn update_diagnostics(
 4168        &mut self,
 4169        language_server_id: LanguageServerId,
 4170        mut params: lsp::PublishDiagnosticsParams,
 4171        disk_based_sources: &[String],
 4172        cx: &mut ModelContext<Self>,
 4173    ) -> Result<()> {
 4174        let abs_path = params
 4175            .uri
 4176            .to_file_path()
 4177            .map_err(|_| anyhow!("URI is not a file"))?;
 4178        let mut diagnostics = Vec::default();
 4179        let mut primary_diagnostic_group_ids = HashMap::default();
 4180        let mut sources_by_group_id = HashMap::default();
 4181        let mut supporting_diagnostics = HashMap::default();
 4182
 4183        // Ensure that primary diagnostics are always the most severe
 4184        params.diagnostics.sort_by_key(|item| item.severity);
 4185
 4186        for diagnostic in &params.diagnostics {
 4187            let source = diagnostic.source.as_ref();
 4188            let code = diagnostic.code.as_ref().map(|code| match code {
 4189                lsp::NumberOrString::Number(code) => code.to_string(),
 4190                lsp::NumberOrString::String(code) => code.clone(),
 4191            });
 4192            let range = range_from_lsp(diagnostic.range);
 4193            let is_supporting = diagnostic
 4194                .related_information
 4195                .as_ref()
 4196                .map_or(false, |infos| {
 4197                    infos.iter().any(|info| {
 4198                        primary_diagnostic_group_ids.contains_key(&(
 4199                            source,
 4200                            code.clone(),
 4201                            range_from_lsp(info.location.range),
 4202                        ))
 4203                    })
 4204                });
 4205
 4206            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
 4207                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
 4208            });
 4209
 4210            if is_supporting {
 4211                supporting_diagnostics.insert(
 4212                    (source, code.clone(), range),
 4213                    (diagnostic.severity, is_unnecessary),
 4214                );
 4215            } else {
 4216                let group_id = post_inc(&mut self.next_diagnostic_group_id);
 4217                let is_disk_based =
 4218                    source.map_or(false, |source| disk_based_sources.contains(source));
 4219
 4220                sources_by_group_id.insert(group_id, source);
 4221                primary_diagnostic_group_ids
 4222                    .insert((source, code.clone(), range.clone()), group_id);
 4223
 4224                diagnostics.push(DiagnosticEntry {
 4225                    range,
 4226                    diagnostic: Diagnostic {
 4227                        source: diagnostic.source.clone(),
 4228                        code: code.clone(),
 4229                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
 4230                        message: diagnostic.message.trim().to_string(),
 4231                        group_id,
 4232                        is_primary: true,
 4233                        is_disk_based,
 4234                        is_unnecessary,
 4235                    },
 4236                });
 4237                if let Some(infos) = &diagnostic.related_information {
 4238                    for info in infos {
 4239                        if info.location.uri == params.uri && !info.message.is_empty() {
 4240                            let range = range_from_lsp(info.location.range);
 4241                            diagnostics.push(DiagnosticEntry {
 4242                                range,
 4243                                diagnostic: Diagnostic {
 4244                                    source: diagnostic.source.clone(),
 4245                                    code: code.clone(),
 4246                                    severity: DiagnosticSeverity::INFORMATION,
 4247                                    message: info.message.trim().to_string(),
 4248                                    group_id,
 4249                                    is_primary: false,
 4250                                    is_disk_based,
 4251                                    is_unnecessary: false,
 4252                                },
 4253                            });
 4254                        }
 4255                    }
 4256                }
 4257            }
 4258        }
 4259
 4260        for entry in &mut diagnostics {
 4261            let diagnostic = &mut entry.diagnostic;
 4262            if !diagnostic.is_primary {
 4263                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
 4264                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
 4265                    source,
 4266                    diagnostic.code.clone(),
 4267                    entry.range.clone(),
 4268                )) {
 4269                    if let Some(severity) = severity {
 4270                        diagnostic.severity = severity;
 4271                    }
 4272                    diagnostic.is_unnecessary = is_unnecessary;
 4273                }
 4274            }
 4275        }
 4276
 4277        self.update_diagnostic_entries(
 4278            language_server_id,
 4279            abs_path,
 4280            params.version,
 4281            diagnostics,
 4282            cx,
 4283        )?;
 4284        Ok(())
 4285    }
 4286
 4287    pub fn update_diagnostic_entries(
 4288        &mut self,
 4289        server_id: LanguageServerId,
 4290        abs_path: PathBuf,
 4291        version: Option<i32>,
 4292        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 4293        cx: &mut ModelContext<Project>,
 4294    ) -> Result<(), anyhow::Error> {
 4295        let (worktree, relative_path) = self
 4296            .find_local_worktree(&abs_path, cx)
 4297            .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
 4298
 4299        let project_path = ProjectPath {
 4300            worktree_id: worktree.read(cx).id(),
 4301            path: relative_path.into(),
 4302        };
 4303
 4304        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
 4305            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
 4306        }
 4307
 4308        let updated = worktree.update(cx, |worktree, cx| {
 4309            worktree
 4310                .as_local_mut()
 4311                .ok_or_else(|| anyhow!("not a local worktree"))?
 4312                .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
 4313        })?;
 4314        if updated {
 4315            cx.emit(Event::DiagnosticsUpdated {
 4316                language_server_id: server_id,
 4317                path: project_path,
 4318            });
 4319        }
 4320        Ok(())
 4321    }
 4322
 4323    fn update_buffer_diagnostics(
 4324        &mut self,
 4325        buffer: &Model<Buffer>,
 4326        server_id: LanguageServerId,
 4327        version: Option<i32>,
 4328        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
 4329        cx: &mut ModelContext<Self>,
 4330    ) -> Result<()> {
 4331        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
 4332            Ordering::Equal
 4333                .then_with(|| b.is_primary.cmp(&a.is_primary))
 4334                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
 4335                .then_with(|| a.severity.cmp(&b.severity))
 4336                .then_with(|| a.message.cmp(&b.message))
 4337        }
 4338
 4339        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
 4340
 4341        diagnostics.sort_unstable_by(|a, b| {
 4342            Ordering::Equal
 4343                .then_with(|| a.range.start.cmp(&b.range.start))
 4344                .then_with(|| b.range.end.cmp(&a.range.end))
 4345                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
 4346        });
 4347
 4348        let mut sanitized_diagnostics = Vec::new();
 4349        let edits_since_save = Patch::new(
 4350            snapshot
 4351                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
 4352                .collect(),
 4353        );
 4354        for entry in diagnostics {
 4355            let start;
 4356            let end;
 4357            if entry.diagnostic.is_disk_based {
 4358                // Some diagnostics are based on files on disk instead of buffers'
 4359                // current contents. Adjust these diagnostics' ranges to reflect
 4360                // any unsaved edits.
 4361                start = edits_since_save.old_to_new(entry.range.start);
 4362                end = edits_since_save.old_to_new(entry.range.end);
 4363            } else {
 4364                start = entry.range.start;
 4365                end = entry.range.end;
 4366            }
 4367
 4368            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
 4369                ..snapshot.clip_point_utf16(end, Bias::Right);
 4370
 4371            // Expand empty ranges by one codepoint
 4372            if range.start == range.end {
 4373                // This will be go to the next boundary when being clipped
 4374                range.end.column += 1;
 4375                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
 4376                if range.start == range.end && range.end.column > 0 {
 4377                    range.start.column -= 1;
 4378                    range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
 4379                }
 4380            }
 4381
 4382            sanitized_diagnostics.push(DiagnosticEntry {
 4383                range,
 4384                diagnostic: entry.diagnostic,
 4385            });
 4386        }
 4387        drop(edits_since_save);
 4388
 4389        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
 4390        buffer.update(cx, |buffer, cx| {
 4391            buffer.update_diagnostics(server_id, set, cx)
 4392        });
 4393        Ok(())
 4394    }
 4395
 4396    pub fn reload_buffers(
 4397        &self,
 4398        buffers: HashSet<Model<Buffer>>,
 4399        push_to_history: bool,
 4400        cx: &mut ModelContext<Self>,
 4401    ) -> Task<Result<ProjectTransaction>> {
 4402        let mut local_buffers = Vec::new();
 4403        let mut remote_buffers = None;
 4404        for buffer_handle in buffers {
 4405            let buffer = buffer_handle.read(cx);
 4406            if buffer.is_dirty() {
 4407                if let Some(file) = File::from_dyn(buffer.file()) {
 4408                    if file.is_local() {
 4409                        local_buffers.push(buffer_handle);
 4410                    } else {
 4411                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
 4412                    }
 4413                }
 4414            }
 4415        }
 4416
 4417        let remote_buffers = self.remote_id().zip(remote_buffers);
 4418        let client = self.client.clone();
 4419
 4420        cx.spawn(move |this, mut cx| async move {
 4421            let mut project_transaction = ProjectTransaction::default();
 4422
 4423            if let Some((project_id, remote_buffers)) = remote_buffers {
 4424                let response = client
 4425                    .request(proto::ReloadBuffers {
 4426                        project_id,
 4427                        buffer_ids: remote_buffers
 4428                            .iter()
 4429                            .filter_map(|buffer| {
 4430                                buffer
 4431                                    .update(&mut cx, |buffer, _| buffer.remote_id().into())
 4432                                    .ok()
 4433                            })
 4434                            .collect(),
 4435                    })
 4436                    .await?
 4437                    .transaction
 4438                    .ok_or_else(|| anyhow!("missing transaction"))?;
 4439                project_transaction = this
 4440                    .update(&mut cx, |this, cx| {
 4441                        this.deserialize_project_transaction(response, push_to_history, cx)
 4442                    })?
 4443                    .await?;
 4444            }
 4445
 4446            for buffer in local_buffers {
 4447                let transaction = buffer
 4448                    .update(&mut cx, |buffer, cx| buffer.reload(cx))?
 4449                    .await?;
 4450                buffer.update(&mut cx, |buffer, cx| {
 4451                    if let Some(transaction) = transaction {
 4452                        if !push_to_history {
 4453                            buffer.forget_transaction(transaction.id);
 4454                        }
 4455                        project_transaction.0.insert(cx.handle(), transaction);
 4456                    }
 4457                })?;
 4458            }
 4459
 4460            Ok(project_transaction)
 4461        })
 4462    }
 4463
 4464    pub fn format(
 4465        &mut self,
 4466        buffers: HashSet<Model<Buffer>>,
 4467        push_to_history: bool,
 4468        trigger: FormatTrigger,
 4469        cx: &mut ModelContext<Project>,
 4470    ) -> Task<anyhow::Result<ProjectTransaction>> {
 4471        if self.is_local() {
 4472            let buffers_with_paths = buffers
 4473                .into_iter()
 4474                .filter_map(|buffer_handle| {
 4475                    let buffer = buffer_handle.read(cx);
 4476                    let file = File::from_dyn(buffer.file())?;
 4477                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
 4478                    Some((buffer_handle, buffer_abs_path))
 4479                })
 4480                .collect::<Vec<_>>();
 4481
 4482            cx.spawn(move |project, mut cx| async move {
 4483                let result = Self::format_locally(
 4484                    project.clone(),
 4485                    buffers_with_paths,
 4486                    push_to_history,
 4487                    trigger,
 4488                    cx.clone(),
 4489                )
 4490                .await;
 4491
 4492                project.update(&mut cx, |project, _| match &result {
 4493                    Ok(_) => project.last_formatting_failure = None,
 4494                    Err(error) => {
 4495                        project.last_formatting_failure.replace(error.to_string());
 4496                    }
 4497                })?;
 4498
 4499                result
 4500            })
 4501        } else {
 4502            let remote_id = self.remote_id();
 4503            let client = self.client.clone();
 4504            cx.spawn(move |this, mut cx| async move {
 4505                let mut project_transaction = ProjectTransaction::default();
 4506                if let Some(project_id) = remote_id {
 4507                    let response = client
 4508                        .request(proto::FormatBuffers {
 4509                            project_id,
 4510                            trigger: trigger as i32,
 4511                            buffer_ids: buffers
 4512                                .iter()
 4513                                .map(|buffer| {
 4514                                    buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
 4515                                })
 4516                                .collect::<Result<_>>()?,
 4517                        })
 4518                        .await?
 4519                        .transaction
 4520                        .ok_or_else(|| anyhow!("missing transaction"))?;
 4521                    project_transaction = this
 4522                        .update(&mut cx, |this, cx| {
 4523                            this.deserialize_project_transaction(response, push_to_history, cx)
 4524                        })?
 4525                        .await?;
 4526                }
 4527                Ok(project_transaction)
 4528            })
 4529        }
 4530    }
 4531
 4532    async fn format_locally(
 4533        project: WeakModel<Project>,
 4534        mut buffers_with_paths: Vec<(Model<Buffer>, Option<PathBuf>)>,
 4535        push_to_history: bool,
 4536        trigger: FormatTrigger,
 4537        mut cx: AsyncAppContext,
 4538    ) -> anyhow::Result<ProjectTransaction> {
 4539        // Do not allow multiple concurrent formatting requests for the
 4540        // same buffer.
 4541        project.update(&mut cx, |this, cx| {
 4542            buffers_with_paths.retain(|(buffer, _)| {
 4543                this.buffers_being_formatted
 4544                    .insert(buffer.read(cx).remote_id())
 4545            });
 4546        })?;
 4547
 4548        let _cleanup = defer({
 4549            let this = project.clone();
 4550            let mut cx = cx.clone();
 4551            let buffers = &buffers_with_paths;
 4552            move || {
 4553                this.update(&mut cx, |this, cx| {
 4554                    for (buffer, _) in buffers {
 4555                        this.buffers_being_formatted
 4556                            .remove(&buffer.read(cx).remote_id());
 4557                    }
 4558                })
 4559                .ok();
 4560            }
 4561        });
 4562
 4563        let mut project_transaction = ProjectTransaction::default();
 4564        for (buffer, buffer_abs_path) in &buffers_with_paths {
 4565            let adapters_and_servers: Vec<_> = project.update(&mut cx, |project, cx| {
 4566                project
 4567                    .language_servers_for_buffer(&buffer.read(cx), cx)
 4568                    .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
 4569                    .collect()
 4570            })?;
 4571
 4572            let settings = buffer.update(&mut cx, |buffer, cx| {
 4573                language_settings(buffer.language(), buffer.file(), cx).clone()
 4574            })?;
 4575
 4576            let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
 4577            let ensure_final_newline = settings.ensure_final_newline_on_save;
 4578            let tab_size = settings.tab_size;
 4579
 4580            // First, format buffer's whitespace according to the settings.
 4581            let trailing_whitespace_diff = if remove_trailing_whitespace {
 4582                Some(
 4583                    buffer
 4584                        .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
 4585                        .await,
 4586                )
 4587            } else {
 4588                None
 4589            };
 4590            let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
 4591                buffer.finalize_last_transaction();
 4592                buffer.start_transaction();
 4593                if let Some(diff) = trailing_whitespace_diff {
 4594                    buffer.apply_diff(diff, cx);
 4595                }
 4596                if ensure_final_newline {
 4597                    buffer.ensure_final_newline(cx);
 4598                }
 4599                buffer.end_transaction(cx)
 4600            })?;
 4601
 4602            // Apply the `code_actions_on_format` before we run the formatter.
 4603            let code_actions = deserialize_code_actions(&settings.code_actions_on_format);
 4604            #[allow(clippy::nonminimal_bool)]
 4605            if !code_actions.is_empty()
 4606                && !(trigger == FormatTrigger::Save && settings.format_on_save == FormatOnSave::Off)
 4607            {
 4608                Self::execute_code_actions_on_servers(
 4609                    &project,
 4610                    &adapters_and_servers,
 4611                    code_actions,
 4612                    buffer,
 4613                    push_to_history,
 4614                    &mut project_transaction,
 4615                    &mut cx,
 4616                )
 4617                .await?;
 4618            }
 4619
 4620            // Apply language-specific formatting using either the primary language server
 4621            // or external command.
 4622            // Except for code actions, which are applied with all connected language servers.
 4623            let primary_language_server = adapters_and_servers
 4624                .first()
 4625                .cloned()
 4626                .map(|(_, lsp)| lsp.clone());
 4627            let server_and_buffer = primary_language_server
 4628                .as_ref()
 4629                .zip(buffer_abs_path.as_ref());
 4630
 4631            let mut format_operation = None;
 4632            match (&settings.formatter, &settings.format_on_save) {
 4633                (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
 4634
 4635                (Formatter::CodeActions(code_actions), FormatOnSave::On | FormatOnSave::Off)
 4636                | (_, FormatOnSave::CodeActions(code_actions)) => {
 4637                    let code_actions = deserialize_code_actions(code_actions);
 4638                    if !code_actions.is_empty() {
 4639                        Self::execute_code_actions_on_servers(
 4640                            &project,
 4641                            &adapters_and_servers,
 4642                            code_actions,
 4643                            buffer,
 4644                            push_to_history,
 4645                            &mut project_transaction,
 4646                            &mut cx,
 4647                        )
 4648                        .await?;
 4649                    }
 4650                }
 4651                (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
 4652                | (_, FormatOnSave::LanguageServer) => {
 4653                    if let Some((language_server, buffer_abs_path)) = server_and_buffer {
 4654                        format_operation = Some(FormatOperation::Lsp(
 4655                            Self::format_via_lsp(
 4656                                &project,
 4657                                buffer,
 4658                                buffer_abs_path,
 4659                                language_server,
 4660                                tab_size,
 4661                                &mut cx,
 4662                            )
 4663                            .await
 4664                            .context("failed to format via language server")?,
 4665                        ));
 4666                    }
 4667                }
 4668
 4669                (
 4670                    Formatter::External { command, arguments },
 4671                    FormatOnSave::On | FormatOnSave::Off,
 4672                )
 4673                | (_, FormatOnSave::External { command, arguments }) => {
 4674                    if let Some(buffer_abs_path) = buffer_abs_path {
 4675                        format_operation = Self::format_via_external_command(
 4676                            buffer,
 4677                            buffer_abs_path,
 4678                            command,
 4679                            arguments,
 4680                            &mut cx,
 4681                        )
 4682                        .await
 4683                        .context(format!(
 4684                            "failed to format via external command {:?}",
 4685                            command
 4686                        ))?
 4687                        .map(FormatOperation::External);
 4688                    }
 4689                }
 4690                (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
 4691                    let prettier =
 4692                        prettier_support::format_with_prettier(&project, buffer, &mut cx).await;
 4693
 4694                    if let Some(operation) = prettier {
 4695                        format_operation = Some(operation?);
 4696                    } else if let Some((language_server, buffer_abs_path)) = server_and_buffer {
 4697                        format_operation = Some(FormatOperation::Lsp(
 4698                            Self::format_via_lsp(
 4699                                &project,
 4700                                buffer,
 4701                                buffer_abs_path,
 4702                                language_server,
 4703                                tab_size,
 4704                                &mut cx,
 4705                            )
 4706                            .await
 4707                            .context("failed to format via language server")?,
 4708                        ));
 4709                    }
 4710                }
 4711                (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
 4712                    let prettier =
 4713                        prettier_support::format_with_prettier(&project, buffer, &mut cx).await;
 4714
 4715                    if let Some(operation) = prettier {
 4716                        format_operation = Some(operation?);
 4717                    }
 4718                }
 4719            };
 4720
 4721            buffer.update(&mut cx, |b, cx| {
 4722                // If the buffer had its whitespace formatted and was edited while the language-specific
 4723                // formatting was being computed, avoid applying the language-specific formatting, because
 4724                // it can't be grouped with the whitespace formatting in the undo history.
 4725                if let Some(transaction_id) = whitespace_transaction_id {
 4726                    if b.peek_undo_stack()
 4727                        .map_or(true, |e| e.transaction_id() != transaction_id)
 4728                    {
 4729                        format_operation.take();
 4730                    }
 4731                }
 4732
 4733                // Apply any language-specific formatting, and group the two formatting operations
 4734                // in the buffer's undo history.
 4735                if let Some(operation) = format_operation {
 4736                    match operation {
 4737                        FormatOperation::Lsp(edits) => {
 4738                            b.edit(edits, None, cx);
 4739                        }
 4740                        FormatOperation::External(diff) => {
 4741                            b.apply_diff(diff, cx);
 4742                        }
 4743                        FormatOperation::Prettier(diff) => {
 4744                            b.apply_diff(diff, cx);
 4745                        }
 4746                    }
 4747
 4748                    if let Some(transaction_id) = whitespace_transaction_id {
 4749                        b.group_until_transaction(transaction_id);
 4750                    } else if let Some(transaction) = project_transaction.0.get(buffer) {
 4751                        b.group_until_transaction(transaction.id)
 4752                    }
 4753                }
 4754
 4755                if let Some(transaction) = b.finalize_last_transaction().cloned() {
 4756                    if !push_to_history {
 4757                        b.forget_transaction(transaction.id);
 4758                    }
 4759                    project_transaction.0.insert(buffer.clone(), transaction);
 4760                }
 4761            })?;
 4762        }
 4763
 4764        Ok(project_transaction)
 4765    }
 4766
 4767    async fn format_via_lsp(
 4768        this: &WeakModel<Self>,
 4769        buffer: &Model<Buffer>,
 4770        abs_path: &Path,
 4771        language_server: &Arc<LanguageServer>,
 4772        tab_size: NonZeroU32,
 4773        cx: &mut AsyncAppContext,
 4774    ) -> Result<Vec<(Range<Anchor>, String)>> {
 4775        let uri = lsp::Url::from_file_path(abs_path)
 4776            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
 4777        let text_document = lsp::TextDocumentIdentifier::new(uri);
 4778        let capabilities = &language_server.capabilities();
 4779
 4780        let formatting_provider = capabilities.document_formatting_provider.as_ref();
 4781        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
 4782
 4783        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
 4784            language_server
 4785                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
 4786                    text_document,
 4787                    options: lsp_command::lsp_formatting_options(tab_size.get()),
 4788                    work_done_progress_params: Default::default(),
 4789                })
 4790                .await?
 4791        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
 4792            let buffer_start = lsp::Position::new(0, 0);
 4793            let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
 4794
 4795            language_server
 4796                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
 4797                    text_document,
 4798                    range: lsp::Range::new(buffer_start, buffer_end),
 4799                    options: lsp_command::lsp_formatting_options(tab_size.get()),
 4800                    work_done_progress_params: Default::default(),
 4801                })
 4802                .await?
 4803        } else {
 4804            None
 4805        };
 4806
 4807        if let Some(lsp_edits) = lsp_edits {
 4808            this.update(cx, |this, cx| {
 4809                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
 4810            })?
 4811            .await
 4812        } else {
 4813            Ok(Vec::new())
 4814        }
 4815    }
 4816
 4817    async fn format_via_external_command(
 4818        buffer: &Model<Buffer>,
 4819        buffer_abs_path: &Path,
 4820        command: &str,
 4821        arguments: &[String],
 4822        cx: &mut AsyncAppContext,
 4823    ) -> Result<Option<Diff>> {
 4824        let working_dir_path = buffer.update(cx, |buffer, cx| {
 4825            let file = File::from_dyn(buffer.file())?;
 4826            let worktree = file.worktree.read(cx).as_local()?;
 4827            let mut worktree_path = worktree.abs_path().to_path_buf();
 4828            if worktree.root_entry()?.is_file() {
 4829                worktree_path.pop();
 4830            }
 4831            Some(worktree_path)
 4832        })?;
 4833
 4834        if let Some(working_dir_path) = working_dir_path {
 4835            let mut child =
 4836                smol::process::Command::new(command)
 4837                    .args(arguments.iter().map(|arg| {
 4838                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
 4839                    }))
 4840                    .current_dir(&working_dir_path)
 4841                    .stdin(smol::process::Stdio::piped())
 4842                    .stdout(smol::process::Stdio::piped())
 4843                    .stderr(smol::process::Stdio::piped())
 4844                    .spawn()?;
 4845            let stdin = child
 4846                .stdin
 4847                .as_mut()
 4848                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
 4849            let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
 4850            for chunk in text.chunks() {
 4851                stdin.write_all(chunk.as_bytes()).await?;
 4852            }
 4853            stdin.flush().await?;
 4854
 4855            let output = child.output().await?;
 4856            if !output.status.success() {
 4857                return Err(anyhow!(
 4858                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
 4859                    output.status.code(),
 4860                    String::from_utf8_lossy(&output.stdout),
 4861                    String::from_utf8_lossy(&output.stderr),
 4862                ));
 4863            }
 4864
 4865            let stdout = String::from_utf8(output.stdout)?;
 4866            Ok(Some(
 4867                buffer
 4868                    .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
 4869                    .await,
 4870            ))
 4871        } else {
 4872            Ok(None)
 4873        }
 4874    }
 4875
 4876    #[inline(never)]
 4877    fn definition_impl(
 4878        &self,
 4879        buffer: &Model<Buffer>,
 4880        position: PointUtf16,
 4881        cx: &mut ModelContext<Self>,
 4882    ) -> Task<Result<Vec<LocationLink>>> {
 4883        self.request_lsp(
 4884            buffer.clone(),
 4885            LanguageServerToQuery::Primary,
 4886            GetDefinition { position },
 4887            cx,
 4888        )
 4889    }
 4890    pub fn definition<T: ToPointUtf16>(
 4891        &self,
 4892        buffer: &Model<Buffer>,
 4893        position: T,
 4894        cx: &mut ModelContext<Self>,
 4895    ) -> Task<Result<Vec<LocationLink>>> {
 4896        let position = position.to_point_utf16(buffer.read(cx));
 4897        self.definition_impl(buffer, position, cx)
 4898    }
 4899
 4900    fn type_definition_impl(
 4901        &self,
 4902        buffer: &Model<Buffer>,
 4903        position: PointUtf16,
 4904        cx: &mut ModelContext<Self>,
 4905    ) -> Task<Result<Vec<LocationLink>>> {
 4906        self.request_lsp(
 4907            buffer.clone(),
 4908            LanguageServerToQuery::Primary,
 4909            GetTypeDefinition { position },
 4910            cx,
 4911        )
 4912    }
 4913
 4914    pub fn type_definition<T: ToPointUtf16>(
 4915        &self,
 4916        buffer: &Model<Buffer>,
 4917        position: T,
 4918        cx: &mut ModelContext<Self>,
 4919    ) -> Task<Result<Vec<LocationLink>>> {
 4920        let position = position.to_point_utf16(buffer.read(cx));
 4921        self.type_definition_impl(buffer, position, cx)
 4922    }
 4923
 4924    fn implementation_impl(
 4925        &self,
 4926        buffer: &Model<Buffer>,
 4927        position: PointUtf16,
 4928        cx: &mut ModelContext<Self>,
 4929    ) -> Task<Result<Vec<LocationLink>>> {
 4930        self.request_lsp(
 4931            buffer.clone(),
 4932            LanguageServerToQuery::Primary,
 4933            GetImplementation { position },
 4934            cx,
 4935        )
 4936    }
 4937
 4938    pub fn implementation<T: ToPointUtf16>(
 4939        &self,
 4940        buffer: &Model<Buffer>,
 4941        position: T,
 4942        cx: &mut ModelContext<Self>,
 4943    ) -> Task<Result<Vec<LocationLink>>> {
 4944        let position = position.to_point_utf16(buffer.read(cx));
 4945        self.implementation_impl(buffer, position, cx)
 4946    }
 4947
 4948    fn references_impl(
 4949        &self,
 4950        buffer: &Model<Buffer>,
 4951        position: PointUtf16,
 4952        cx: &mut ModelContext<Self>,
 4953    ) -> Task<Result<Vec<Location>>> {
 4954        self.request_lsp(
 4955            buffer.clone(),
 4956            LanguageServerToQuery::Primary,
 4957            GetReferences { position },
 4958            cx,
 4959        )
 4960    }
 4961    pub fn references<T: ToPointUtf16>(
 4962        &self,
 4963        buffer: &Model<Buffer>,
 4964        position: T,
 4965        cx: &mut ModelContext<Self>,
 4966    ) -> Task<Result<Vec<Location>>> {
 4967        let position = position.to_point_utf16(buffer.read(cx));
 4968        self.references_impl(buffer, position, cx)
 4969    }
 4970
 4971    fn document_highlights_impl(
 4972        &self,
 4973        buffer: &Model<Buffer>,
 4974        position: PointUtf16,
 4975        cx: &mut ModelContext<Self>,
 4976    ) -> Task<Result<Vec<DocumentHighlight>>> {
 4977        self.request_lsp(
 4978            buffer.clone(),
 4979            LanguageServerToQuery::Primary,
 4980            GetDocumentHighlights { position },
 4981            cx,
 4982        )
 4983    }
 4984
 4985    pub fn document_highlights<T: ToPointUtf16>(
 4986        &self,
 4987        buffer: &Model<Buffer>,
 4988        position: T,
 4989        cx: &mut ModelContext<Self>,
 4990    ) -> Task<Result<Vec<DocumentHighlight>>> {
 4991        let position = position.to_point_utf16(buffer.read(cx));
 4992        self.document_highlights_impl(buffer, position, cx)
 4993    }
 4994
 4995    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
 4996        let language_registry = self.languages.clone();
 4997
 4998        if self.is_local() {
 4999            let mut requests = Vec::new();
 5000            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
 5001                let Some(worktree_handle) = self.worktree_for_id(*worktree_id, cx) else {
 5002                    continue;
 5003                };
 5004                let worktree = worktree_handle.read(cx);
 5005                if !worktree.is_visible() {
 5006                    continue;
 5007                }
 5008                let Some(worktree) = worktree.as_local() else {
 5009                    continue;
 5010                };
 5011                let worktree_abs_path = worktree.abs_path().clone();
 5012
 5013                let (adapter, language, server) = match self.language_servers.get(server_id) {
 5014                    Some(LanguageServerState::Running {
 5015                        adapter,
 5016                        language,
 5017                        server,
 5018                        ..
 5019                    }) => (adapter.clone(), language.clone(), server),
 5020
 5021                    _ => continue,
 5022                };
 5023
 5024                requests.push(
 5025                    server
 5026                        .request::<lsp::request::WorkspaceSymbolRequest>(
 5027                            lsp::WorkspaceSymbolParams {
 5028                                query: query.to_string(),
 5029                                ..Default::default()
 5030                            },
 5031                        )
 5032                        .log_err()
 5033                        .map(move |response| {
 5034                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
 5035                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
 5036                                    flat_responses.into_iter().map(|lsp_symbol| {
 5037                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
 5038                                    }).collect::<Vec<_>>()
 5039                                }
 5040                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
 5041                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
 5042                                        let location = match lsp_symbol.location {
 5043                                            OneOf::Left(location) => location,
 5044                                            OneOf::Right(_) => {
 5045                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
 5046                                                return None
 5047                                            }
 5048                                        };
 5049                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
 5050                                    }).collect::<Vec<_>>()
 5051                                }
 5052                            }).unwrap_or_default();
 5053
 5054                            (
 5055                                adapter,
 5056                                language,
 5057                                worktree_handle.downgrade(),
 5058                                worktree_abs_path,
 5059                                lsp_symbols,
 5060                            )
 5061                        }),
 5062                );
 5063            }
 5064
 5065            cx.spawn(move |this, mut cx| async move {
 5066                let responses = futures::future::join_all(requests).await;
 5067                let this = match this.upgrade() {
 5068                    Some(this) => this,
 5069                    None => return Ok(Vec::new()),
 5070                };
 5071
 5072                let mut symbols = Vec::new();
 5073                for (adapter, adapter_language, source_worktree, worktree_abs_path, lsp_symbols) in
 5074                    responses
 5075                {
 5076                    let core_symbols = this.update(&mut cx, |this, cx| {
 5077                        lsp_symbols
 5078                            .into_iter()
 5079                            .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
 5080                                let abs_path = symbol_location.uri.to_file_path().ok()?;
 5081                                let source_worktree = source_worktree.upgrade()?;
 5082                                let source_worktree_id = source_worktree.read(cx).id();
 5083
 5084                                let path;
 5085                                let worktree;
 5086                                if let Some((tree, rel_path)) =
 5087                                    this.find_local_worktree(&abs_path, cx)
 5088                                {
 5089                                    worktree = tree;
 5090                                    path = rel_path;
 5091                                } else {
 5092                                    worktree = source_worktree.clone();
 5093                                    path = relativize_path(&worktree_abs_path, &abs_path);
 5094                                }
 5095
 5096                                let worktree_id = worktree.read(cx).id();
 5097                                let project_path = ProjectPath {
 5098                                    worktree_id,
 5099                                    path: path.into(),
 5100                                };
 5101                                let signature = this.symbol_signature(&project_path);
 5102                                Some(CoreSymbol {
 5103                                    language_server_name: adapter.name.clone(),
 5104                                    source_worktree_id,
 5105                                    path: project_path,
 5106                                    kind: symbol_kind,
 5107                                    name: symbol_name,
 5108                                    range: range_from_lsp(symbol_location.range),
 5109                                    signature,
 5110                                })
 5111                            })
 5112                            .collect()
 5113                    })?;
 5114
 5115                    populate_labels_for_symbols(
 5116                        core_symbols,
 5117                        &language_registry,
 5118                        Some(adapter_language),
 5119                        Some(adapter),
 5120                        &mut symbols,
 5121                    )
 5122                    .await;
 5123                }
 5124
 5125                Ok(symbols)
 5126            })
 5127        } else if let Some(project_id) = self.remote_id() {
 5128            let request = self.client.request(proto::GetProjectSymbols {
 5129                project_id,
 5130                query: query.to_string(),
 5131            });
 5132            cx.foreground_executor().spawn(async move {
 5133                let response = request.await?;
 5134                let mut symbols = Vec::new();
 5135                let core_symbols = response
 5136                    .symbols
 5137                    .into_iter()
 5138                    .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
 5139                    .collect::<Vec<_>>();
 5140                populate_labels_for_symbols(
 5141                    core_symbols,
 5142                    &language_registry,
 5143                    None,
 5144                    None,
 5145                    &mut symbols,
 5146                )
 5147                .await;
 5148                Ok(symbols)
 5149            })
 5150        } else {
 5151            Task::ready(Ok(Default::default()))
 5152        }
 5153    }
 5154
 5155    pub fn open_buffer_for_symbol(
 5156        &mut self,
 5157        symbol: &Symbol,
 5158        cx: &mut ModelContext<Self>,
 5159    ) -> Task<Result<Model<Buffer>>> {
 5160        if self.is_local() {
 5161            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
 5162                symbol.source_worktree_id,
 5163                symbol.language_server_name.clone(),
 5164            )) {
 5165                *id
 5166            } else {
 5167                return Task::ready(Err(anyhow!(
 5168                    "language server for worktree and language not found"
 5169                )));
 5170            };
 5171
 5172            let worktree_abs_path = if let Some(worktree_abs_path) = self
 5173                .worktree_for_id(symbol.path.worktree_id, cx)
 5174                .and_then(|worktree| worktree.read(cx).as_local())
 5175                .map(|local_worktree| local_worktree.abs_path())
 5176            {
 5177                worktree_abs_path
 5178            } else {
 5179                return Task::ready(Err(anyhow!("worktree not found for symbol")));
 5180            };
 5181
 5182            let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
 5183            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
 5184                uri
 5185            } else {
 5186                return Task::ready(Err(anyhow!("invalid symbol path")));
 5187            };
 5188
 5189            self.open_local_buffer_via_lsp(
 5190                symbol_uri,
 5191                language_server_id,
 5192                symbol.language_server_name.clone(),
 5193                cx,
 5194            )
 5195        } else if let Some(project_id) = self.remote_id() {
 5196            let request = self.client.request(proto::OpenBufferForSymbol {
 5197                project_id,
 5198                symbol: Some(serialize_symbol(symbol)),
 5199            });
 5200            cx.spawn(move |this, mut cx| async move {
 5201                let response = request.await?;
 5202                let buffer_id = BufferId::new(response.buffer_id)?;
 5203                this.update(&mut cx, |this, cx| {
 5204                    this.wait_for_remote_buffer(buffer_id, cx)
 5205                })?
 5206                .await
 5207            })
 5208        } else {
 5209            Task::ready(Err(anyhow!("project does not have a remote id")))
 5210        }
 5211    }
 5212
 5213    fn hover_impl(
 5214        &self,
 5215        buffer: &Model<Buffer>,
 5216        position: PointUtf16,
 5217        cx: &mut ModelContext<Self>,
 5218    ) -> Task<Vec<Hover>> {
 5219        if self.is_local() {
 5220            let all_actions_task = self.request_multiple_lsp_locally(
 5221                &buffer,
 5222                Some(position),
 5223                |server_capabilities| match server_capabilities.hover_provider {
 5224                    Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
 5225                    Some(lsp::HoverProviderCapability::Options(_)) => true,
 5226                    None => false,
 5227                },
 5228                GetHover { position },
 5229                cx,
 5230            );
 5231            cx.spawn(|_, _| async move {
 5232                all_actions_task
 5233                    .await
 5234                    .into_iter()
 5235                    .filter_map(|hover| remove_empty_hover_blocks(hover?))
 5236                    .collect()
 5237            })
 5238        } else if let Some(project_id) = self.remote_id() {
 5239            let request_task = self.client().request(proto::MultiLspQuery {
 5240                buffer_id: buffer.read(cx).remote_id().into(),
 5241                version: serialize_version(&buffer.read(cx).version()),
 5242                project_id,
 5243                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5244                    proto::AllLanguageServers {},
 5245                )),
 5246                request: Some(proto::multi_lsp_query::Request::GetHover(
 5247                    GetHover { position }.to_proto(project_id, buffer.read(cx)),
 5248                )),
 5249            });
 5250            let buffer = buffer.clone();
 5251            cx.spawn(|weak_project, cx| async move {
 5252                let Some(project) = weak_project.upgrade() else {
 5253                    return Vec::new();
 5254                };
 5255                join_all(
 5256                    request_task
 5257                        .await
 5258                        .log_err()
 5259                        .map(|response| response.responses)
 5260                        .unwrap_or_default()
 5261                        .into_iter()
 5262                        .filter_map(|lsp_response| match lsp_response.response? {
 5263                            proto::lsp_response::Response::GetHoverResponse(response) => {
 5264                                Some(response)
 5265                            }
 5266                            unexpected => {
 5267                                debug_panic!("Unexpected response: {unexpected:?}");
 5268                                None
 5269                            }
 5270                        })
 5271                        .map(|hover_response| {
 5272                            let response = GetHover { position }.response_from_proto(
 5273                                hover_response,
 5274                                project.clone(),
 5275                                buffer.clone(),
 5276                                cx.clone(),
 5277                            );
 5278                            async move {
 5279                                response
 5280                                    .await
 5281                                    .log_err()
 5282                                    .flatten()
 5283                                    .and_then(remove_empty_hover_blocks)
 5284                            }
 5285                        }),
 5286                )
 5287                .await
 5288                .into_iter()
 5289                .flatten()
 5290                .collect()
 5291            })
 5292        } else {
 5293            log::error!("cannot show hovers: project does not have a remote id");
 5294            Task::ready(Vec::new())
 5295        }
 5296    }
 5297
 5298    pub fn hover<T: ToPointUtf16>(
 5299        &self,
 5300        buffer: &Model<Buffer>,
 5301        position: T,
 5302        cx: &mut ModelContext<Self>,
 5303    ) -> Task<Vec<Hover>> {
 5304        let position = position.to_point_utf16(buffer.read(cx));
 5305        self.hover_impl(buffer, position, cx)
 5306    }
 5307
 5308    #[inline(never)]
 5309    fn completions_impl(
 5310        &self,
 5311        buffer: &Model<Buffer>,
 5312        position: PointUtf16,
 5313        cx: &mut ModelContext<Self>,
 5314    ) -> Task<Result<Vec<Completion>>> {
 5315        let language_registry = self.languages.clone();
 5316
 5317        if self.is_local() {
 5318            let snapshot = buffer.read(cx).snapshot();
 5319            let offset = position.to_offset(&snapshot);
 5320            let scope = snapshot.language_scope_at(offset);
 5321            let language = snapshot.language().cloned();
 5322
 5323            let server_ids: Vec<_> = self
 5324                .language_servers_for_buffer(buffer.read(cx), cx)
 5325                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
 5326                .filter(|(adapter, _)| {
 5327                    scope
 5328                        .as_ref()
 5329                        .map(|scope| scope.language_allowed(&adapter.name))
 5330                        .unwrap_or(true)
 5331                })
 5332                .map(|(_, server)| server.server_id())
 5333                .collect();
 5334
 5335            let buffer = buffer.clone();
 5336            cx.spawn(move |this, mut cx| async move {
 5337                let mut tasks = Vec::with_capacity(server_ids.len());
 5338                this.update(&mut cx, |this, cx| {
 5339                    for server_id in server_ids {
 5340                        let lsp_adapter = this.language_server_adapter_for_id(server_id);
 5341                        tasks.push((
 5342                            lsp_adapter,
 5343                            this.request_lsp(
 5344                                buffer.clone(),
 5345                                LanguageServerToQuery::Other(server_id),
 5346                                GetCompletions { position },
 5347                                cx,
 5348                            ),
 5349                        ));
 5350                    }
 5351                })?;
 5352
 5353                let mut completions = Vec::new();
 5354                for (lsp_adapter, task) in tasks {
 5355                    if let Ok(new_completions) = task.await {
 5356                        populate_labels_for_completions(
 5357                            new_completions,
 5358                            &language_registry,
 5359                            language.clone(),
 5360                            lsp_adapter,
 5361                            &mut completions,
 5362                        )
 5363                        .await;
 5364                    }
 5365                }
 5366
 5367                Ok(completions)
 5368            })
 5369        } else if let Some(project_id) = self.remote_id() {
 5370            let task = self.send_lsp_proto_request(
 5371                buffer.clone(),
 5372                project_id,
 5373                GetCompletions { position },
 5374                cx,
 5375            );
 5376            let language = buffer.read(cx).language().cloned();
 5377
 5378            // In the future, we should provide project guests with the names of LSP adapters,
 5379            // so that they can use the correct LSP adapter when computing labels. For now,
 5380            // guests just use the first LSP adapter associated with the buffer's language.
 5381            let lsp_adapter = language
 5382                .as_ref()
 5383                .and_then(|language| language_registry.lsp_adapters(language).first().cloned());
 5384
 5385            cx.foreground_executor().spawn(async move {
 5386                let completions = task.await?;
 5387                let mut result = Vec::new();
 5388                populate_labels_for_completions(
 5389                    completions,
 5390                    &language_registry,
 5391                    language,
 5392                    lsp_adapter,
 5393                    &mut result,
 5394                )
 5395                .await;
 5396                Ok(result)
 5397            })
 5398        } else {
 5399            Task::ready(Ok(Default::default()))
 5400        }
 5401    }
 5402
 5403    pub fn completions<T: ToOffset + ToPointUtf16>(
 5404        &self,
 5405        buffer: &Model<Buffer>,
 5406        position: T,
 5407        cx: &mut ModelContext<Self>,
 5408    ) -> Task<Result<Vec<Completion>>> {
 5409        let position = position.to_point_utf16(buffer.read(cx));
 5410        self.completions_impl(buffer, position, cx)
 5411    }
 5412
 5413    pub fn resolve_completions(
 5414        &self,
 5415        completion_indices: Vec<usize>,
 5416        completions: Arc<RwLock<Box<[Completion]>>>,
 5417        cx: &mut ModelContext<Self>,
 5418    ) -> Task<Result<bool>> {
 5419        let client = self.client();
 5420        let language_registry = self.languages().clone();
 5421
 5422        let is_remote = self.is_remote();
 5423        let project_id = self.remote_id();
 5424
 5425        cx.spawn(move |this, mut cx| async move {
 5426            let mut did_resolve = false;
 5427            if is_remote {
 5428                let project_id =
 5429                    project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
 5430
 5431                for completion_index in completion_indices {
 5432                    let (server_id, completion) = {
 5433                        let completions_guard = completions.read();
 5434                        let completion = &completions_guard[completion_index];
 5435                        if completion.documentation.is_some() {
 5436                            continue;
 5437                        }
 5438
 5439                        did_resolve = true;
 5440                        let server_id = completion.server_id;
 5441                        let completion = completion.lsp_completion.clone();
 5442
 5443                        (server_id, completion)
 5444                    };
 5445
 5446                    Self::resolve_completion_documentation_remote(
 5447                        project_id,
 5448                        server_id,
 5449                        completions.clone(),
 5450                        completion_index,
 5451                        completion,
 5452                        client.clone(),
 5453                        language_registry.clone(),
 5454                    )
 5455                    .await;
 5456                }
 5457            } else {
 5458                for completion_index in completion_indices {
 5459                    let (server_id, completion) = {
 5460                        let completions_guard = completions.read();
 5461                        let completion = &completions_guard[completion_index];
 5462                        if completion.documentation.is_some() {
 5463                            continue;
 5464                        }
 5465
 5466                        let server_id = completion.server_id;
 5467                        let completion = completion.lsp_completion.clone();
 5468
 5469                        (server_id, completion)
 5470                    };
 5471
 5472                    let server = this
 5473                        .read_with(&mut cx, |project, _| {
 5474                            project.language_server_for_id(server_id)
 5475                        })
 5476                        .ok()
 5477                        .flatten();
 5478                    let Some(server) = server else {
 5479                        continue;
 5480                    };
 5481
 5482                    did_resolve = true;
 5483                    Self::resolve_completion_documentation_local(
 5484                        server,
 5485                        completions.clone(),
 5486                        completion_index,
 5487                        completion,
 5488                        language_registry.clone(),
 5489                    )
 5490                    .await;
 5491                }
 5492            }
 5493
 5494            Ok(did_resolve)
 5495        })
 5496    }
 5497
 5498    async fn resolve_completion_documentation_local(
 5499        server: Arc<lsp::LanguageServer>,
 5500        completions: Arc<RwLock<Box<[Completion]>>>,
 5501        completion_index: usize,
 5502        completion: lsp::CompletionItem,
 5503        language_registry: Arc<LanguageRegistry>,
 5504    ) {
 5505        let can_resolve = server
 5506            .capabilities()
 5507            .completion_provider
 5508            .as_ref()
 5509            .and_then(|options| options.resolve_provider)
 5510            .unwrap_or(false);
 5511        if !can_resolve {
 5512            return;
 5513        }
 5514
 5515        let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
 5516        let Some(completion_item) = request.await.log_err() else {
 5517            return;
 5518        };
 5519
 5520        if let Some(lsp_documentation) = completion_item.documentation {
 5521            let documentation = language::prepare_completion_documentation(
 5522                &lsp_documentation,
 5523                &language_registry,
 5524                None, // TODO: Try to reasonably work out which language the completion is for
 5525            )
 5526            .await;
 5527
 5528            let mut completions = completions.write();
 5529            let completion = &mut completions[completion_index];
 5530            completion.documentation = Some(documentation);
 5531        } else {
 5532            let mut completions = completions.write();
 5533            let completion = &mut completions[completion_index];
 5534            completion.documentation = Some(Documentation::Undocumented);
 5535        }
 5536    }
 5537
 5538    async fn resolve_completion_documentation_remote(
 5539        project_id: u64,
 5540        server_id: LanguageServerId,
 5541        completions: Arc<RwLock<Box<[Completion]>>>,
 5542        completion_index: usize,
 5543        completion: lsp::CompletionItem,
 5544        client: Arc<Client>,
 5545        language_registry: Arc<LanguageRegistry>,
 5546    ) {
 5547        let request = proto::ResolveCompletionDocumentation {
 5548            project_id,
 5549            language_server_id: server_id.0 as u64,
 5550            lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
 5551        };
 5552
 5553        let Some(response) = client
 5554            .request(request)
 5555            .await
 5556            .context("completion documentation resolve proto request")
 5557            .log_err()
 5558        else {
 5559            return;
 5560        };
 5561
 5562        if response.text.is_empty() {
 5563            let mut completions = completions.write();
 5564            let completion = &mut completions[completion_index];
 5565            completion.documentation = Some(Documentation::Undocumented);
 5566        }
 5567
 5568        let documentation = if response.is_markdown {
 5569            Documentation::MultiLineMarkdown(
 5570                markdown::parse_markdown(&response.text, &language_registry, None).await,
 5571            )
 5572        } else if response.text.lines().count() <= 1 {
 5573            Documentation::SingleLine(response.text)
 5574        } else {
 5575            Documentation::MultiLinePlainText(response.text)
 5576        };
 5577
 5578        let mut completions = completions.write();
 5579        let completion = &mut completions[completion_index];
 5580        completion.documentation = Some(documentation);
 5581    }
 5582
 5583    pub fn apply_additional_edits_for_completion(
 5584        &self,
 5585        buffer_handle: Model<Buffer>,
 5586        completion: Completion,
 5587        push_to_history: bool,
 5588        cx: &mut ModelContext<Self>,
 5589    ) -> Task<Result<Option<Transaction>>> {
 5590        let buffer = buffer_handle.read(cx);
 5591        let buffer_id = buffer.remote_id();
 5592
 5593        if self.is_local() {
 5594            let server_id = completion.server_id;
 5595            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
 5596                Some((_, server)) => server.clone(),
 5597                _ => return Task::ready(Ok(Default::default())),
 5598            };
 5599
 5600            cx.spawn(move |this, mut cx| async move {
 5601                let can_resolve = lang_server
 5602                    .capabilities()
 5603                    .completion_provider
 5604                    .as_ref()
 5605                    .and_then(|options| options.resolve_provider)
 5606                    .unwrap_or(false);
 5607                let additional_text_edits = if can_resolve {
 5608                    lang_server
 5609                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
 5610                        .await?
 5611                        .additional_text_edits
 5612                } else {
 5613                    completion.lsp_completion.additional_text_edits
 5614                };
 5615                if let Some(edits) = additional_text_edits {
 5616                    let edits = this
 5617                        .update(&mut cx, |this, cx| {
 5618                            this.edits_from_lsp(
 5619                                &buffer_handle,
 5620                                edits,
 5621                                lang_server.server_id(),
 5622                                None,
 5623                                cx,
 5624                            )
 5625                        })?
 5626                        .await?;
 5627
 5628                    buffer_handle.update(&mut cx, |buffer, cx| {
 5629                        buffer.finalize_last_transaction();
 5630                        buffer.start_transaction();
 5631
 5632                        for (range, text) in edits {
 5633                            let primary = &completion.old_range;
 5634                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
 5635                                && primary.end.cmp(&range.start, buffer).is_ge();
 5636                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
 5637                                && range.end.cmp(&primary.end, buffer).is_ge();
 5638
 5639                            //Skip additional edits which overlap with the primary completion edit
 5640                            //https://github.com/zed-industries/zed/pull/1871
 5641                            if !start_within && !end_within {
 5642                                buffer.edit([(range, text)], None, cx);
 5643                            }
 5644                        }
 5645
 5646                        let transaction = if buffer.end_transaction(cx).is_some() {
 5647                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 5648                            if !push_to_history {
 5649                                buffer.forget_transaction(transaction.id);
 5650                            }
 5651                            Some(transaction)
 5652                        } else {
 5653                            None
 5654                        };
 5655                        Ok(transaction)
 5656                    })?
 5657                } else {
 5658                    Ok(None)
 5659                }
 5660            })
 5661        } else if let Some(project_id) = self.remote_id() {
 5662            let client = self.client.clone();
 5663            cx.spawn(move |_, mut cx| async move {
 5664                let response = client
 5665                    .request(proto::ApplyCompletionAdditionalEdits {
 5666                        project_id,
 5667                        buffer_id: buffer_id.into(),
 5668                        completion: Some(Self::serialize_completion(&CoreCompletion {
 5669                            old_range: completion.old_range,
 5670                            new_text: completion.new_text,
 5671                            server_id: completion.server_id,
 5672                            lsp_completion: completion.lsp_completion,
 5673                        })),
 5674                    })
 5675                    .await?;
 5676
 5677                if let Some(transaction) = response.transaction {
 5678                    let transaction = language::proto::deserialize_transaction(transaction)?;
 5679                    buffer_handle
 5680                        .update(&mut cx, |buffer, _| {
 5681                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 5682                        })?
 5683                        .await?;
 5684                    if push_to_history {
 5685                        buffer_handle.update(&mut cx, |buffer, _| {
 5686                            buffer.push_transaction(transaction.clone(), Instant::now());
 5687                        })?;
 5688                    }
 5689                    Ok(Some(transaction))
 5690                } else {
 5691                    Ok(None)
 5692                }
 5693            })
 5694        } else {
 5695            Task::ready(Err(anyhow!("project does not have a remote id")))
 5696        }
 5697    }
 5698
 5699    fn code_actions_impl(
 5700        &self,
 5701        buffer_handle: &Model<Buffer>,
 5702        range: Range<Anchor>,
 5703        cx: &mut ModelContext<Self>,
 5704    ) -> Task<Vec<CodeAction>> {
 5705        if self.is_local() {
 5706            let all_actions_task = self.request_multiple_lsp_locally(
 5707                &buffer_handle,
 5708                Some(range.start),
 5709                GetCodeActions::supports_code_actions,
 5710                GetCodeActions {
 5711                    range: range.clone(),
 5712                    kinds: None,
 5713                },
 5714                cx,
 5715            );
 5716            cx.spawn(|_, _| async move { all_actions_task.await.into_iter().flatten().collect() })
 5717        } else if let Some(project_id) = self.remote_id() {
 5718            let request_task = self.client().request(proto::MultiLspQuery {
 5719                buffer_id: buffer_handle.read(cx).remote_id().into(),
 5720                version: serialize_version(&buffer_handle.read(cx).version()),
 5721                project_id,
 5722                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5723                    proto::AllLanguageServers {},
 5724                )),
 5725                request: Some(proto::multi_lsp_query::Request::GetCodeActions(
 5726                    GetCodeActions {
 5727                        range: range.clone(),
 5728                        kinds: None,
 5729                    }
 5730                    .to_proto(project_id, buffer_handle.read(cx)),
 5731                )),
 5732            });
 5733            let buffer = buffer_handle.clone();
 5734            cx.spawn(|weak_project, cx| async move {
 5735                let Some(project) = weak_project.upgrade() else {
 5736                    return Vec::new();
 5737                };
 5738                join_all(
 5739                    request_task
 5740                        .await
 5741                        .log_err()
 5742                        .map(|response| response.responses)
 5743                        .unwrap_or_default()
 5744                        .into_iter()
 5745                        .filter_map(|lsp_response| match lsp_response.response? {
 5746                            proto::lsp_response::Response::GetCodeActionsResponse(response) => {
 5747                                Some(response)
 5748                            }
 5749                            unexpected => {
 5750                                debug_panic!("Unexpected response: {unexpected:?}");
 5751                                None
 5752                            }
 5753                        })
 5754                        .map(|code_actions_response| {
 5755                            let response = GetCodeActions {
 5756                                range: range.clone(),
 5757                                kinds: None,
 5758                            }
 5759                            .response_from_proto(
 5760                                code_actions_response,
 5761                                project.clone(),
 5762                                buffer.clone(),
 5763                                cx.clone(),
 5764                            );
 5765                            async move { response.await.log_err().unwrap_or_default() }
 5766                        }),
 5767                )
 5768                .await
 5769                .into_iter()
 5770                .flatten()
 5771                .collect()
 5772            })
 5773        } else {
 5774            log::error!("cannot fetch actions: project does not have a remote id");
 5775            Task::ready(Vec::new())
 5776        }
 5777    }
 5778
 5779    pub fn code_actions<T: Clone + ToOffset>(
 5780        &self,
 5781        buffer_handle: &Model<Buffer>,
 5782        range: Range<T>,
 5783        cx: &mut ModelContext<Self>,
 5784    ) -> Task<Vec<CodeAction>> {
 5785        let buffer = buffer_handle.read(cx);
 5786        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
 5787        self.code_actions_impl(buffer_handle, range, cx)
 5788    }
 5789
 5790    pub fn apply_code_action(
 5791        &self,
 5792        buffer_handle: Model<Buffer>,
 5793        mut action: CodeAction,
 5794        push_to_history: bool,
 5795        cx: &mut ModelContext<Self>,
 5796    ) -> Task<Result<ProjectTransaction>> {
 5797        if self.is_local() {
 5798            let buffer = buffer_handle.read(cx);
 5799            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
 5800                self.language_server_for_buffer(buffer, action.server_id, cx)
 5801            {
 5802                (adapter.clone(), server.clone())
 5803            } else {
 5804                return Task::ready(Ok(Default::default()));
 5805            };
 5806            cx.spawn(move |this, mut cx| async move {
 5807                Self::try_resolve_code_action(&lang_server, &mut action)
 5808                    .await
 5809                    .context("resolving a code action")?;
 5810                if let Some(edit) = action.lsp_action.edit {
 5811                    if edit.changes.is_some() || edit.document_changes.is_some() {
 5812                        return Self::deserialize_workspace_edit(
 5813                            this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
 5814                            edit,
 5815                            push_to_history,
 5816                            lsp_adapter.clone(),
 5817                            lang_server.clone(),
 5818                            &mut cx,
 5819                        )
 5820                        .await;
 5821                    }
 5822                }
 5823
 5824                if let Some(command) = action.lsp_action.command {
 5825                    this.update(&mut cx, |this, _| {
 5826                        this.last_workspace_edits_by_language_server
 5827                            .remove(&lang_server.server_id());
 5828                    })?;
 5829
 5830                    let result = lang_server
 5831                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 5832                            command: command.command,
 5833                            arguments: command.arguments.unwrap_or_default(),
 5834                            ..Default::default()
 5835                        })
 5836                        .await;
 5837
 5838                    if let Err(err) = result {
 5839                        // TODO: LSP ERROR
 5840                        return Err(err);
 5841                    }
 5842
 5843                    return this.update(&mut cx, |this, _| {
 5844                        this.last_workspace_edits_by_language_server
 5845                            .remove(&lang_server.server_id())
 5846                            .unwrap_or_default()
 5847                    });
 5848                }
 5849
 5850                Ok(ProjectTransaction::default())
 5851            })
 5852        } else if let Some(project_id) = self.remote_id() {
 5853            let client = self.client.clone();
 5854            let request = proto::ApplyCodeAction {
 5855                project_id,
 5856                buffer_id: buffer_handle.read(cx).remote_id().into(),
 5857                action: Some(Self::serialize_code_action(&action)),
 5858            };
 5859            cx.spawn(move |this, mut cx| async move {
 5860                let response = client
 5861                    .request(request)
 5862                    .await?
 5863                    .transaction
 5864                    .ok_or_else(|| anyhow!("missing transaction"))?;
 5865                this.update(&mut cx, |this, cx| {
 5866                    this.deserialize_project_transaction(response, push_to_history, cx)
 5867                })?
 5868                .await
 5869            })
 5870        } else {
 5871            Task::ready(Err(anyhow!("project does not have a remote id")))
 5872        }
 5873    }
 5874
 5875    fn apply_on_type_formatting(
 5876        &self,
 5877        buffer: Model<Buffer>,
 5878        position: Anchor,
 5879        trigger: String,
 5880        cx: &mut ModelContext<Self>,
 5881    ) -> Task<Result<Option<Transaction>>> {
 5882        if self.is_local() {
 5883            cx.spawn(move |this, mut cx| async move {
 5884                // Do not allow multiple concurrent formatting requests for the
 5885                // same buffer.
 5886                this.update(&mut cx, |this, cx| {
 5887                    this.buffers_being_formatted
 5888                        .insert(buffer.read(cx).remote_id())
 5889                })?;
 5890
 5891                let _cleanup = defer({
 5892                    let this = this.clone();
 5893                    let mut cx = cx.clone();
 5894                    let closure_buffer = buffer.clone();
 5895                    move || {
 5896                        this.update(&mut cx, |this, cx| {
 5897                            this.buffers_being_formatted
 5898                                .remove(&closure_buffer.read(cx).remote_id());
 5899                        })
 5900                        .ok();
 5901                    }
 5902                });
 5903
 5904                buffer
 5905                    .update(&mut cx, |buffer, _| {
 5906                        buffer.wait_for_edits(Some(position.timestamp))
 5907                    })?
 5908                    .await?;
 5909                this.update(&mut cx, |this, cx| {
 5910                    let position = position.to_point_utf16(buffer.read(cx));
 5911                    this.on_type_format(buffer, position, trigger, false, cx)
 5912                })?
 5913                .await
 5914            })
 5915        } else if let Some(project_id) = self.remote_id() {
 5916            let client = self.client.clone();
 5917            let request = proto::OnTypeFormatting {
 5918                project_id,
 5919                buffer_id: buffer.read(cx).remote_id().into(),
 5920                position: Some(serialize_anchor(&position)),
 5921                trigger,
 5922                version: serialize_version(&buffer.read(cx).version()),
 5923            };
 5924            cx.spawn(move |_, _| async move {
 5925                client
 5926                    .request(request)
 5927                    .await?
 5928                    .transaction
 5929                    .map(language::proto::deserialize_transaction)
 5930                    .transpose()
 5931            })
 5932        } else {
 5933            Task::ready(Err(anyhow!("project does not have a remote id")))
 5934        }
 5935    }
 5936
 5937    async fn deserialize_edits(
 5938        this: Model<Self>,
 5939        buffer_to_edit: Model<Buffer>,
 5940        edits: Vec<lsp::TextEdit>,
 5941        push_to_history: bool,
 5942        _: Arc<CachedLspAdapter>,
 5943        language_server: Arc<LanguageServer>,
 5944        cx: &mut AsyncAppContext,
 5945    ) -> Result<Option<Transaction>> {
 5946        let edits = this
 5947            .update(cx, |this, cx| {
 5948                this.edits_from_lsp(
 5949                    &buffer_to_edit,
 5950                    edits,
 5951                    language_server.server_id(),
 5952                    None,
 5953                    cx,
 5954                )
 5955            })?
 5956            .await?;
 5957
 5958        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
 5959            buffer.finalize_last_transaction();
 5960            buffer.start_transaction();
 5961            for (range, text) in edits {
 5962                buffer.edit([(range, text)], None, cx);
 5963            }
 5964
 5965            if buffer.end_transaction(cx).is_some() {
 5966                let transaction = buffer.finalize_last_transaction().unwrap().clone();
 5967                if !push_to_history {
 5968                    buffer.forget_transaction(transaction.id);
 5969                }
 5970                Some(transaction)
 5971            } else {
 5972                None
 5973            }
 5974        })?;
 5975
 5976        Ok(transaction)
 5977    }
 5978
 5979    async fn deserialize_workspace_edit(
 5980        this: Model<Self>,
 5981        edit: lsp::WorkspaceEdit,
 5982        push_to_history: bool,
 5983        lsp_adapter: Arc<CachedLspAdapter>,
 5984        language_server: Arc<LanguageServer>,
 5985        cx: &mut AsyncAppContext,
 5986    ) -> Result<ProjectTransaction> {
 5987        let fs = this.update(cx, |this, _| this.fs.clone())?;
 5988        let mut operations = Vec::new();
 5989        if let Some(document_changes) = edit.document_changes {
 5990            match document_changes {
 5991                lsp::DocumentChanges::Edits(edits) => {
 5992                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
 5993                }
 5994                lsp::DocumentChanges::Operations(ops) => operations = ops,
 5995            }
 5996        } else if let Some(changes) = edit.changes {
 5997            operations.extend(changes.into_iter().map(|(uri, edits)| {
 5998                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
 5999                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
 6000                        uri,
 6001                        version: None,
 6002                    },
 6003                    edits: edits.into_iter().map(OneOf::Left).collect(),
 6004                })
 6005            }));
 6006        }
 6007
 6008        let mut project_transaction = ProjectTransaction::default();
 6009        for operation in operations {
 6010            match operation {
 6011                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
 6012                    let abs_path = op
 6013                        .uri
 6014                        .to_file_path()
 6015                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6016
 6017                    if let Some(parent_path) = abs_path.parent() {
 6018                        fs.create_dir(parent_path).await?;
 6019                    }
 6020                    if abs_path.ends_with("/") {
 6021                        fs.create_dir(&abs_path).await?;
 6022                    } else {
 6023                        fs.create_file(
 6024                            &abs_path,
 6025                            op.options
 6026                                .map(|options| fs::CreateOptions {
 6027                                    overwrite: options.overwrite.unwrap_or(false),
 6028                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 6029                                })
 6030                                .unwrap_or_default(),
 6031                        )
 6032                        .await?;
 6033                    }
 6034                }
 6035
 6036                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
 6037                    let source_abs_path = op
 6038                        .old_uri
 6039                        .to_file_path()
 6040                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6041                    let target_abs_path = op
 6042                        .new_uri
 6043                        .to_file_path()
 6044                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6045                    fs.rename(
 6046                        &source_abs_path,
 6047                        &target_abs_path,
 6048                        op.options
 6049                            .map(|options| fs::RenameOptions {
 6050                                overwrite: options.overwrite.unwrap_or(false),
 6051                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 6052                            })
 6053                            .unwrap_or_default(),
 6054                    )
 6055                    .await?;
 6056                }
 6057
 6058                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
 6059                    let abs_path = op
 6060                        .uri
 6061                        .to_file_path()
 6062                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6063                    let options = op
 6064                        .options
 6065                        .map(|options| fs::RemoveOptions {
 6066                            recursive: options.recursive.unwrap_or(false),
 6067                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
 6068                        })
 6069                        .unwrap_or_default();
 6070                    if abs_path.ends_with("/") {
 6071                        fs.remove_dir(&abs_path, options).await?;
 6072                    } else {
 6073                        fs.remove_file(&abs_path, options).await?;
 6074                    }
 6075                }
 6076
 6077                lsp::DocumentChangeOperation::Edit(op) => {
 6078                    let buffer_to_edit = this
 6079                        .update(cx, |this, cx| {
 6080                            this.open_local_buffer_via_lsp(
 6081                                op.text_document.uri,
 6082                                language_server.server_id(),
 6083                                lsp_adapter.name.clone(),
 6084                                cx,
 6085                            )
 6086                        })?
 6087                        .await?;
 6088
 6089                    let edits = this
 6090                        .update(cx, |this, cx| {
 6091                            let edits = op.edits.into_iter().map(|edit| match edit {
 6092                                OneOf::Left(edit) => edit,
 6093                                OneOf::Right(edit) => edit.text_edit,
 6094                            });
 6095                            this.edits_from_lsp(
 6096                                &buffer_to_edit,
 6097                                edits,
 6098                                language_server.server_id(),
 6099                                op.text_document.version,
 6100                                cx,
 6101                            )
 6102                        })?
 6103                        .await?;
 6104
 6105                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
 6106                        buffer.finalize_last_transaction();
 6107                        buffer.start_transaction();
 6108                        for (range, text) in edits {
 6109                            buffer.edit([(range, text)], None, cx);
 6110                        }
 6111                        let transaction = if buffer.end_transaction(cx).is_some() {
 6112                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6113                            if !push_to_history {
 6114                                buffer.forget_transaction(transaction.id);
 6115                            }
 6116                            Some(transaction)
 6117                        } else {
 6118                            None
 6119                        };
 6120
 6121                        transaction
 6122                    })?;
 6123                    if let Some(transaction) = transaction {
 6124                        project_transaction.0.insert(buffer_to_edit, transaction);
 6125                    }
 6126                }
 6127            }
 6128        }
 6129
 6130        Ok(project_transaction)
 6131    }
 6132
 6133    fn prepare_rename_impl(
 6134        &self,
 6135        buffer: Model<Buffer>,
 6136        position: PointUtf16,
 6137        cx: &mut ModelContext<Self>,
 6138    ) -> Task<Result<Option<Range<Anchor>>>> {
 6139        self.request_lsp(
 6140            buffer,
 6141            LanguageServerToQuery::Primary,
 6142            PrepareRename { position },
 6143            cx,
 6144        )
 6145    }
 6146    pub fn prepare_rename<T: ToPointUtf16>(
 6147        &self,
 6148        buffer: Model<Buffer>,
 6149        position: T,
 6150        cx: &mut ModelContext<Self>,
 6151    ) -> Task<Result<Option<Range<Anchor>>>> {
 6152        let position = position.to_point_utf16(buffer.read(cx));
 6153        self.prepare_rename_impl(buffer, position, cx)
 6154    }
 6155
 6156    fn perform_rename_impl(
 6157        &self,
 6158        buffer: Model<Buffer>,
 6159        position: PointUtf16,
 6160        new_name: String,
 6161        push_to_history: bool,
 6162        cx: &mut ModelContext<Self>,
 6163    ) -> Task<Result<ProjectTransaction>> {
 6164        let position = position.to_point_utf16(buffer.read(cx));
 6165        self.request_lsp(
 6166            buffer,
 6167            LanguageServerToQuery::Primary,
 6168            PerformRename {
 6169                position,
 6170                new_name,
 6171                push_to_history,
 6172            },
 6173            cx,
 6174        )
 6175    }
 6176    pub fn perform_rename<T: ToPointUtf16>(
 6177        &self,
 6178        buffer: Model<Buffer>,
 6179        position: T,
 6180        new_name: String,
 6181        push_to_history: bool,
 6182        cx: &mut ModelContext<Self>,
 6183    ) -> Task<Result<ProjectTransaction>> {
 6184        let position = position.to_point_utf16(buffer.read(cx));
 6185        self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
 6186    }
 6187
 6188    pub fn on_type_format_impl(
 6189        &self,
 6190        buffer: Model<Buffer>,
 6191        position: PointUtf16,
 6192        trigger: String,
 6193        push_to_history: bool,
 6194        cx: &mut ModelContext<Self>,
 6195    ) -> Task<Result<Option<Transaction>>> {
 6196        let tab_size = buffer.update(cx, |buffer, cx| {
 6197            language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx).tab_size
 6198        });
 6199        self.request_lsp(
 6200            buffer.clone(),
 6201            LanguageServerToQuery::Primary,
 6202            OnTypeFormatting {
 6203                position,
 6204                trigger,
 6205                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
 6206                push_to_history,
 6207            },
 6208            cx,
 6209        )
 6210    }
 6211
 6212    pub fn on_type_format<T: ToPointUtf16>(
 6213        &self,
 6214        buffer: Model<Buffer>,
 6215        position: T,
 6216        trigger: String,
 6217        push_to_history: bool,
 6218        cx: &mut ModelContext<Self>,
 6219    ) -> Task<Result<Option<Transaction>>> {
 6220        let position = position.to_point_utf16(buffer.read(cx));
 6221        self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
 6222    }
 6223
 6224    pub fn inlay_hints<T: ToOffset>(
 6225        &self,
 6226        buffer_handle: Model<Buffer>,
 6227        range: Range<T>,
 6228        cx: &mut ModelContext<Self>,
 6229    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 6230        let buffer = buffer_handle.read(cx);
 6231        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
 6232        self.inlay_hints_impl(buffer_handle, range, cx)
 6233    }
 6234    fn inlay_hints_impl(
 6235        &self,
 6236        buffer_handle: Model<Buffer>,
 6237        range: Range<Anchor>,
 6238        cx: &mut ModelContext<Self>,
 6239    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 6240        let buffer = buffer_handle.read(cx);
 6241        let range_start = range.start;
 6242        let range_end = range.end;
 6243        let buffer_id = buffer.remote_id().into();
 6244        let lsp_request = InlayHints { range };
 6245
 6246        if self.is_local() {
 6247            let lsp_request_task = self.request_lsp(
 6248                buffer_handle.clone(),
 6249                LanguageServerToQuery::Primary,
 6250                lsp_request,
 6251                cx,
 6252            );
 6253            cx.spawn(move |_, mut cx| async move {
 6254                buffer_handle
 6255                    .update(&mut cx, |buffer, _| {
 6256                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
 6257                    })?
 6258                    .await
 6259                    .context("waiting for inlay hint request range edits")?;
 6260                lsp_request_task.await.context("inlay hints LSP request")
 6261            })
 6262        } else if let Some(project_id) = self.remote_id() {
 6263            let client = self.client.clone();
 6264            let request = proto::InlayHints {
 6265                project_id,
 6266                buffer_id,
 6267                start: Some(serialize_anchor(&range_start)),
 6268                end: Some(serialize_anchor(&range_end)),
 6269                version: serialize_version(&buffer_handle.read(cx).version()),
 6270            };
 6271            cx.spawn(move |project, cx| async move {
 6272                let response = client
 6273                    .request(request)
 6274                    .await
 6275                    .context("inlay hints proto request")?;
 6276                LspCommand::response_from_proto(
 6277                    lsp_request,
 6278                    response,
 6279                    project.upgrade().ok_or_else(|| anyhow!("No project"))?,
 6280                    buffer_handle.clone(),
 6281                    cx.clone(),
 6282                )
 6283                .await
 6284                .context("inlay hints proto response conversion")
 6285            })
 6286        } else {
 6287            Task::ready(Err(anyhow!("project does not have a remote id")))
 6288        }
 6289    }
 6290
 6291    pub fn resolve_inlay_hint(
 6292        &self,
 6293        hint: InlayHint,
 6294        buffer_handle: Model<Buffer>,
 6295        server_id: LanguageServerId,
 6296        cx: &mut ModelContext<Self>,
 6297    ) -> Task<anyhow::Result<InlayHint>> {
 6298        if self.is_local() {
 6299            let buffer = buffer_handle.read(cx);
 6300            let (_, lang_server) = if let Some((adapter, server)) =
 6301                self.language_server_for_buffer(buffer, server_id, cx)
 6302            {
 6303                (adapter.clone(), server.clone())
 6304            } else {
 6305                return Task::ready(Ok(hint));
 6306            };
 6307            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
 6308                return Task::ready(Ok(hint));
 6309            }
 6310
 6311            let buffer_snapshot = buffer.snapshot();
 6312            cx.spawn(move |_, mut cx| async move {
 6313                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
 6314                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
 6315                );
 6316                let resolved_hint = resolve_task
 6317                    .await
 6318                    .context("inlay hint resolve LSP request")?;
 6319                let resolved_hint = InlayHints::lsp_to_project_hint(
 6320                    resolved_hint,
 6321                    &buffer_handle,
 6322                    server_id,
 6323                    ResolveState::Resolved,
 6324                    false,
 6325                    &mut cx,
 6326                )
 6327                .await?;
 6328                Ok(resolved_hint)
 6329            })
 6330        } else if let Some(project_id) = self.remote_id() {
 6331            let client = self.client.clone();
 6332            let request = proto::ResolveInlayHint {
 6333                project_id,
 6334                buffer_id: buffer_handle.read(cx).remote_id().into(),
 6335                language_server_id: server_id.0 as u64,
 6336                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
 6337            };
 6338            cx.spawn(move |_, _| async move {
 6339                let response = client
 6340                    .request(request)
 6341                    .await
 6342                    .context("inlay hints proto request")?;
 6343                match response.hint {
 6344                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
 6345                        .context("inlay hints proto resolve response conversion"),
 6346                    None => Ok(hint),
 6347                }
 6348            })
 6349        } else {
 6350            Task::ready(Err(anyhow!("project does not have a remote id")))
 6351        }
 6352    }
 6353
 6354    #[allow(clippy::type_complexity)]
 6355    pub fn search(
 6356        &self,
 6357        query: SearchQuery,
 6358        cx: &mut ModelContext<Self>,
 6359    ) -> Receiver<SearchResult> {
 6360        if self.is_local() {
 6361            self.search_local(query, cx)
 6362        } else if let Some(project_id) = self.remote_id() {
 6363            let (tx, rx) = smol::channel::unbounded();
 6364            let request = self.client.request(query.to_proto(project_id));
 6365            cx.spawn(move |this, mut cx| async move {
 6366                let response = request.await?;
 6367                let mut result = HashMap::default();
 6368                for location in response.locations {
 6369                    let buffer_id = BufferId::new(location.buffer_id)?;
 6370                    let target_buffer = this
 6371                        .update(&mut cx, |this, cx| {
 6372                            this.wait_for_remote_buffer(buffer_id, cx)
 6373                        })?
 6374                        .await?;
 6375                    let start = location
 6376                        .start
 6377                        .and_then(deserialize_anchor)
 6378                        .ok_or_else(|| anyhow!("missing target start"))?;
 6379                    let end = location
 6380                        .end
 6381                        .and_then(deserialize_anchor)
 6382                        .ok_or_else(|| anyhow!("missing target end"))?;
 6383                    result
 6384                        .entry(target_buffer)
 6385                        .or_insert(Vec::new())
 6386                        .push(start..end)
 6387                }
 6388                for (buffer, ranges) in result {
 6389                    let _ = tx.send(SearchResult::Buffer { buffer, ranges }).await;
 6390                }
 6391
 6392                if response.limit_reached {
 6393                    let _ = tx.send(SearchResult::LimitReached).await;
 6394                }
 6395
 6396                Result::<(), anyhow::Error>::Ok(())
 6397            })
 6398            .detach_and_log_err(cx);
 6399            rx
 6400        } else {
 6401            unimplemented!();
 6402        }
 6403    }
 6404
 6405    pub fn search_local(
 6406        &self,
 6407        query: SearchQuery,
 6408        cx: &mut ModelContext<Self>,
 6409    ) -> Receiver<SearchResult> {
 6410        // Local search is split into several phases.
 6411        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
 6412        // and the second phase that finds positions of all the matches found in the candidate files.
 6413        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
 6414        //
 6415        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
 6416        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
 6417        //
 6418        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
 6419        //    Then, we go through a worktree and check for files that do match a predicate. If the file had an opened version, we skip the scan
 6420        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
 6421        // 2. At this point, we have a list of all potentially matching buffers/files.
 6422        //    We sort that list by buffer path - this list is retained for later use.
 6423        //    We ensure that all buffers are now opened and available in project.
 6424        // 3. We run a scan over all the candidate buffers on multiple background threads.
 6425        //    We cannot assume that there will even be a match - while at least one match
 6426        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
 6427        //    There is also an auxiliary background thread responsible for result gathering.
 6428        //    This is where the sorted list of buffers comes into play to maintain sorted order; Whenever this background thread receives a notification (buffer has/doesn't have matches),
 6429        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
 6430        //    As soon as the match info on next position in sorted order becomes available, it reports it (if it's a match) or skips to the next
 6431        //    entry - which might already be available thanks to out-of-order processing.
 6432        //
 6433        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
 6434        // This however would mean that project search (that is the main user of this function) would have to do the sorting itself, on the go.
 6435        // This isn't as straightforward as running an insertion sort sadly, and would also mean that it would have to care about maintaining match index
 6436        // in face of constantly updating list of sorted matches.
 6437        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
 6438        let snapshots = self
 6439            .visible_worktrees(cx)
 6440            .filter_map(|tree| {
 6441                let tree = tree.read(cx).as_local()?;
 6442                Some(tree.snapshot())
 6443            })
 6444            .collect::<Vec<_>>();
 6445        let include_root = snapshots.len() > 1;
 6446
 6447        let background = cx.background_executor().clone();
 6448        let path_count: usize = snapshots
 6449            .iter()
 6450            .map(|s| {
 6451                if query.include_ignored() {
 6452                    s.file_count()
 6453                } else {
 6454                    s.visible_file_count()
 6455                }
 6456            })
 6457            .sum();
 6458        if path_count == 0 {
 6459            let (_, rx) = smol::channel::bounded(1024);
 6460            return rx;
 6461        }
 6462        let workers = background.num_cpus().min(path_count);
 6463        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
 6464        let mut unnamed_files = vec![];
 6465        let opened_buffers = self
 6466            .opened_buffers
 6467            .iter()
 6468            .filter_map(|(_, b)| {
 6469                let buffer = b.upgrade()?;
 6470                let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
 6471                    let is_ignored = buffer
 6472                        .project_path(cx)
 6473                        .and_then(|path| self.entry_for_path(&path, cx))
 6474                        .map_or(false, |entry| entry.is_ignored);
 6475                    (is_ignored, buffer.snapshot())
 6476                });
 6477                if is_ignored && !query.include_ignored() {
 6478                    return None;
 6479                } else if let Some(file) = snapshot.file() {
 6480                    let matched_path = if include_root {
 6481                        query.file_matches(Some(&file.full_path(cx)))
 6482                    } else {
 6483                        query.file_matches(Some(file.path()))
 6484                    };
 6485
 6486                    if matched_path {
 6487                        Some((file.path().clone(), (buffer, snapshot)))
 6488                    } else {
 6489                        None
 6490                    }
 6491                } else {
 6492                    unnamed_files.push(buffer);
 6493                    None
 6494                }
 6495            })
 6496            .collect();
 6497        cx.background_executor()
 6498            .spawn(Self::background_search(
 6499                unnamed_files,
 6500                opened_buffers,
 6501                cx.background_executor().clone(),
 6502                self.fs.clone(),
 6503                workers,
 6504                query.clone(),
 6505                include_root,
 6506                path_count,
 6507                snapshots,
 6508                matching_paths_tx,
 6509            ))
 6510            .detach();
 6511
 6512        let (result_tx, result_rx) = smol::channel::bounded(1024);
 6513
 6514        cx.spawn(|this, mut cx| async move {
 6515            const MAX_SEARCH_RESULT_FILES: usize = 5_000;
 6516            const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
 6517
 6518            let mut matching_paths = matching_paths_rx
 6519                .take(MAX_SEARCH_RESULT_FILES + 1)
 6520                .collect::<Vec<_>>()
 6521                .await;
 6522            let mut limit_reached = if matching_paths.len() > MAX_SEARCH_RESULT_FILES {
 6523                matching_paths.pop();
 6524                true
 6525            } else {
 6526                false
 6527            };
 6528            matching_paths.sort_by_key(|candidate| (candidate.is_ignored(), candidate.path()));
 6529
 6530            let mut range_count = 0;
 6531            let query = Arc::new(query);
 6532
 6533            // Now that we know what paths match the query, we will load at most
 6534            // 64 buffers at a time to avoid overwhelming the main thread. For each
 6535            // opened buffer, we will spawn a background task that retrieves all the
 6536            // ranges in the buffer matched by the query.
 6537            'outer: for matching_paths_chunk in matching_paths.chunks(64) {
 6538                let mut chunk_results = Vec::new();
 6539                for matching_path in matching_paths_chunk {
 6540                    let query = query.clone();
 6541                    let buffer = match matching_path {
 6542                        SearchMatchCandidate::OpenBuffer { buffer, .. } => {
 6543                            Task::ready(Ok(buffer.clone()))
 6544                        }
 6545                        SearchMatchCandidate::Path {
 6546                            worktree_id, path, ..
 6547                        } => this.update(&mut cx, |this, cx| {
 6548                            this.open_buffer((*worktree_id, path.clone()), cx)
 6549                        })?,
 6550                    };
 6551
 6552                    chunk_results.push(cx.spawn(|cx| async move {
 6553                        let buffer = buffer.await?;
 6554                        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
 6555                        let ranges = cx
 6556                            .background_executor()
 6557                            .spawn(async move {
 6558                                query
 6559                                    .search(&snapshot, None)
 6560                                    .await
 6561                                    .iter()
 6562                                    .map(|range| {
 6563                                        snapshot.anchor_before(range.start)
 6564                                            ..snapshot.anchor_after(range.end)
 6565                                    })
 6566                                    .collect::<Vec<_>>()
 6567                            })
 6568                            .await;
 6569                        anyhow::Ok((buffer, ranges))
 6570                    }));
 6571                }
 6572
 6573                let chunk_results = futures::future::join_all(chunk_results).await;
 6574                for result in chunk_results {
 6575                    if let Some((buffer, ranges)) = result.log_err() {
 6576                        range_count += ranges.len();
 6577                        result_tx
 6578                            .send(SearchResult::Buffer { buffer, ranges })
 6579                            .await?;
 6580                        if range_count > MAX_SEARCH_RESULT_RANGES {
 6581                            limit_reached = true;
 6582                            break 'outer;
 6583                        }
 6584                    }
 6585                }
 6586            }
 6587
 6588            if limit_reached {
 6589                result_tx.send(SearchResult::LimitReached).await?;
 6590            }
 6591
 6592            anyhow::Ok(())
 6593        })
 6594        .detach();
 6595
 6596        result_rx
 6597    }
 6598
 6599    /// Pick paths that might potentially contain a match of a given search query.
 6600    #[allow(clippy::too_many_arguments)]
 6601    async fn background_search(
 6602        unnamed_buffers: Vec<Model<Buffer>>,
 6603        opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
 6604        executor: BackgroundExecutor,
 6605        fs: Arc<dyn Fs>,
 6606        workers: usize,
 6607        query: SearchQuery,
 6608        include_root: bool,
 6609        path_count: usize,
 6610        snapshots: Vec<LocalSnapshot>,
 6611        matching_paths_tx: Sender<SearchMatchCandidate>,
 6612    ) {
 6613        let fs = &fs;
 6614        let query = &query;
 6615        let matching_paths_tx = &matching_paths_tx;
 6616        let snapshots = &snapshots;
 6617        for buffer in unnamed_buffers {
 6618            matching_paths_tx
 6619                .send(SearchMatchCandidate::OpenBuffer {
 6620                    buffer: buffer.clone(),
 6621                    path: None,
 6622                })
 6623                .await
 6624                .log_err();
 6625        }
 6626        for (path, (buffer, _)) in opened_buffers.iter() {
 6627            matching_paths_tx
 6628                .send(SearchMatchCandidate::OpenBuffer {
 6629                    buffer: buffer.clone(),
 6630                    path: Some(path.clone()),
 6631                })
 6632                .await
 6633                .log_err();
 6634        }
 6635
 6636        let paths_per_worker = (path_count + workers - 1) / workers;
 6637
 6638        executor
 6639            .scoped(|scope| {
 6640                let max_concurrent_workers = Arc::new(Semaphore::new(workers));
 6641
 6642                for worker_ix in 0..workers {
 6643                    let worker_start_ix = worker_ix * paths_per_worker;
 6644                    let worker_end_ix = worker_start_ix + paths_per_worker;
 6645                    let opened_buffers = opened_buffers.clone();
 6646                    let limiter = Arc::clone(&max_concurrent_workers);
 6647                    scope.spawn({
 6648                        async move {
 6649                            let _guard = limiter.acquire().await;
 6650                            search_snapshots(
 6651                                snapshots,
 6652                                worker_start_ix,
 6653                                worker_end_ix,
 6654                                query,
 6655                                matching_paths_tx,
 6656                                &opened_buffers,
 6657                                include_root,
 6658                                fs,
 6659                            )
 6660                            .await;
 6661                        }
 6662                    });
 6663                }
 6664
 6665                if query.include_ignored() {
 6666                    for snapshot in snapshots {
 6667                        for ignored_entry in snapshot.entries(true).filter(|e| e.is_ignored) {
 6668                            let limiter = Arc::clone(&max_concurrent_workers);
 6669                            scope.spawn(async move {
 6670                                let _guard = limiter.acquire().await;
 6671                                search_ignored_entry(
 6672                                    snapshot,
 6673                                    ignored_entry,
 6674                                    fs,
 6675                                    query,
 6676                                    matching_paths_tx,
 6677                                )
 6678                                .await;
 6679                            });
 6680                        }
 6681                    }
 6682                }
 6683            })
 6684            .await;
 6685    }
 6686
 6687    pub fn request_lsp<R: LspCommand>(
 6688        &self,
 6689        buffer_handle: Model<Buffer>,
 6690        server: LanguageServerToQuery,
 6691        request: R,
 6692        cx: &mut ModelContext<Self>,
 6693    ) -> Task<Result<R::Response>>
 6694    where
 6695        <R::LspRequest as lsp::request::Request>::Result: Send,
 6696        <R::LspRequest as lsp::request::Request>::Params: Send,
 6697    {
 6698        let buffer = buffer_handle.read(cx);
 6699        if self.is_local() {
 6700            let language_server = match server {
 6701                LanguageServerToQuery::Primary => {
 6702                    match self.primary_language_server_for_buffer(buffer, cx) {
 6703                        Some((_, server)) => Some(Arc::clone(server)),
 6704                        None => return Task::ready(Ok(Default::default())),
 6705                    }
 6706                }
 6707                LanguageServerToQuery::Other(id) => self
 6708                    .language_server_for_buffer(buffer, id, cx)
 6709                    .map(|(_, server)| Arc::clone(server)),
 6710            };
 6711            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
 6712            if let (Some(file), Some(language_server)) = (file, language_server) {
 6713                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
 6714                return cx.spawn(move |this, cx| async move {
 6715                    if !request.check_capabilities(language_server.capabilities()) {
 6716                        return Ok(Default::default());
 6717                    }
 6718
 6719                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
 6720                    let response = match result {
 6721                        Ok(response) => response,
 6722
 6723                        Err(err) => {
 6724                            log::warn!(
 6725                                "Generic lsp request to {} failed: {}",
 6726                                language_server.name(),
 6727                                err
 6728                            );
 6729                            return Err(err);
 6730                        }
 6731                    };
 6732
 6733                    request
 6734                        .response_from_lsp(
 6735                            response,
 6736                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
 6737                            buffer_handle,
 6738                            language_server.server_id(),
 6739                            cx,
 6740                        )
 6741                        .await
 6742                });
 6743            }
 6744        } else if let Some(project_id) = self.remote_id() {
 6745            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
 6746        }
 6747
 6748        Task::ready(Ok(Default::default()))
 6749    }
 6750
 6751    fn request_multiple_lsp_locally<P, R>(
 6752        &self,
 6753        buffer: &Model<Buffer>,
 6754        position: Option<P>,
 6755        server_capabilities_check: fn(&ServerCapabilities) -> bool,
 6756        request: R,
 6757        cx: &mut ModelContext<'_, Self>,
 6758    ) -> Task<Vec<R::Response>>
 6759    where
 6760        P: ToOffset,
 6761        R: LspCommand + Clone,
 6762        <R::LspRequest as lsp::request::Request>::Result: Send,
 6763        <R::LspRequest as lsp::request::Request>::Params: Send,
 6764    {
 6765        if !self.is_local() {
 6766            debug_panic!("Should not request multiple lsp commands in non-local project");
 6767            return Task::ready(Vec::new());
 6768        }
 6769        let snapshot = buffer.read(cx).snapshot();
 6770        let scope = position.and_then(|position| snapshot.language_scope_at(position));
 6771        let mut response_results = self
 6772            .language_servers_for_buffer(buffer.read(cx), cx)
 6773            .filter(|(_, server)| server_capabilities_check(server.capabilities()))
 6774            .filter(|(adapter, _)| {
 6775                scope
 6776                    .as_ref()
 6777                    .map(|scope| scope.language_allowed(&adapter.name))
 6778                    .unwrap_or(true)
 6779            })
 6780            .map(|(_, server)| server.server_id())
 6781            .map(|server_id| {
 6782                self.request_lsp(
 6783                    buffer.clone(),
 6784                    LanguageServerToQuery::Other(server_id),
 6785                    request.clone(),
 6786                    cx,
 6787                )
 6788            })
 6789            .collect::<FuturesUnordered<_>>();
 6790
 6791        return cx.spawn(|_, _| async move {
 6792            let mut responses = Vec::with_capacity(response_results.len());
 6793            while let Some(response_result) = response_results.next().await {
 6794                if let Some(response) = response_result.log_err() {
 6795                    responses.push(response);
 6796                }
 6797            }
 6798            responses
 6799        });
 6800    }
 6801
 6802    fn send_lsp_proto_request<R: LspCommand>(
 6803        &self,
 6804        buffer: Model<Buffer>,
 6805        project_id: u64,
 6806        request: R,
 6807        cx: &mut ModelContext<'_, Project>,
 6808    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
 6809        let rpc = self.client.clone();
 6810        let message = request.to_proto(project_id, buffer.read(cx));
 6811        cx.spawn(move |this, mut cx| async move {
 6812            // Ensure the project is still alive by the time the task
 6813            // is scheduled.
 6814            this.upgrade().context("project dropped")?;
 6815            let response = rpc.request(message).await?;
 6816            let this = this.upgrade().context("project dropped")?;
 6817            if this.update(&mut cx, |this, _| this.is_disconnected())? {
 6818                Err(anyhow!("disconnected before completing request"))
 6819            } else {
 6820                request
 6821                    .response_from_proto(response, this, buffer, cx)
 6822                    .await
 6823            }
 6824        })
 6825    }
 6826
 6827    pub fn find_or_create_local_worktree(
 6828        &mut self,
 6829        abs_path: impl AsRef<Path>,
 6830        visible: bool,
 6831        cx: &mut ModelContext<Self>,
 6832    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
 6833        let abs_path = abs_path.as_ref();
 6834        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
 6835            Task::ready(Ok((tree, relative_path)))
 6836        } else {
 6837            let worktree = self.create_local_worktree(abs_path, visible, cx);
 6838            cx.background_executor()
 6839                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
 6840        }
 6841    }
 6842
 6843    pub fn find_local_worktree(
 6844        &self,
 6845        abs_path: &Path,
 6846        cx: &AppContext,
 6847    ) -> Option<(Model<Worktree>, PathBuf)> {
 6848        for tree in &self.worktrees {
 6849            if let Some(tree) = tree.upgrade() {
 6850                if let Some(relative_path) = tree
 6851                    .read(cx)
 6852                    .as_local()
 6853                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
 6854                {
 6855                    return Some((tree.clone(), relative_path.into()));
 6856                }
 6857            }
 6858        }
 6859        None
 6860    }
 6861
 6862    pub fn is_shared(&self) -> bool {
 6863        match &self.client_state {
 6864            ProjectClientState::Shared { .. } => true,
 6865            ProjectClientState::Local | ProjectClientState::Remote { .. } => false,
 6866        }
 6867    }
 6868
 6869    fn create_local_worktree(
 6870        &mut self,
 6871        abs_path: impl AsRef<Path>,
 6872        visible: bool,
 6873        cx: &mut ModelContext<Self>,
 6874    ) -> Task<Result<Model<Worktree>>> {
 6875        let fs = self.fs.clone();
 6876        let client = self.client.clone();
 6877        let next_entry_id = self.next_entry_id.clone();
 6878        let path: Arc<Path> = abs_path.as_ref().into();
 6879        let task = self
 6880            .loading_local_worktrees
 6881            .entry(path.clone())
 6882            .or_insert_with(|| {
 6883                cx.spawn(move |project, mut cx| {
 6884                    async move {
 6885                        let worktree = Worktree::local(
 6886                            client.clone(),
 6887                            path.clone(),
 6888                            visible,
 6889                            fs,
 6890                            next_entry_id,
 6891                            &mut cx,
 6892                        )
 6893                        .await;
 6894
 6895                        project.update(&mut cx, |project, _| {
 6896                            project.loading_local_worktrees.remove(&path);
 6897                        })?;
 6898
 6899                        let worktree = worktree?;
 6900                        project
 6901                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
 6902
 6903                        if visible {
 6904                            cx.update(|cx| {
 6905                                cx.add_recent_document(&path);
 6906                            })
 6907                            .log_err();
 6908                        }
 6909
 6910                        Ok(worktree)
 6911                    }
 6912                    .map_err(Arc::new)
 6913                })
 6914                .shared()
 6915            })
 6916            .clone();
 6917        cx.background_executor().spawn(async move {
 6918            match task.await {
 6919                Ok(worktree) => Ok(worktree),
 6920                Err(err) => Err(anyhow!("{}", err)),
 6921            }
 6922        })
 6923    }
 6924
 6925    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
 6926        let mut servers_to_remove = HashMap::default();
 6927        let mut servers_to_preserve = HashSet::default();
 6928        for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
 6929            if worktree_id == &id_to_remove {
 6930                servers_to_remove.insert(server_id, server_name.clone());
 6931            } else {
 6932                servers_to_preserve.insert(server_id);
 6933            }
 6934        }
 6935        servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
 6936        for (server_id_to_remove, server_name) in servers_to_remove {
 6937            self.language_server_ids
 6938                .remove(&(id_to_remove, server_name));
 6939            self.language_server_statuses.remove(&server_id_to_remove);
 6940            self.language_server_watched_paths
 6941                .remove(&server_id_to_remove);
 6942            self.last_workspace_edits_by_language_server
 6943                .remove(&server_id_to_remove);
 6944            self.language_servers.remove(&server_id_to_remove);
 6945            cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
 6946        }
 6947
 6948        let mut prettier_instances_to_clean = FuturesUnordered::new();
 6949        if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
 6950            for path in prettier_paths.iter().flatten() {
 6951                if let Some(prettier_instance) = self.prettier_instances.remove(path) {
 6952                    prettier_instances_to_clean.push(async move {
 6953                        prettier_instance
 6954                            .server()
 6955                            .await
 6956                            .map(|server| server.server_id())
 6957                    });
 6958                }
 6959            }
 6960        }
 6961        cx.spawn(|project, mut cx| async move {
 6962            while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
 6963                if let Some(prettier_server_id) = prettier_server_id {
 6964                    project
 6965                        .update(&mut cx, |project, cx| {
 6966                            project
 6967                                .supplementary_language_servers
 6968                                .remove(&prettier_server_id);
 6969                            cx.emit(Event::LanguageServerRemoved(prettier_server_id));
 6970                        })
 6971                        .ok();
 6972                }
 6973            }
 6974        })
 6975        .detach();
 6976
 6977        self.task_inventory().update(cx, |inventory, _| {
 6978            inventory.remove_worktree_sources(id_to_remove);
 6979        });
 6980
 6981        self.worktrees.retain(|worktree| {
 6982            if let Some(worktree) = worktree.upgrade() {
 6983                let id = worktree.read(cx).id();
 6984                if id == id_to_remove {
 6985                    cx.emit(Event::WorktreeRemoved(id));
 6986                    false
 6987                } else {
 6988                    true
 6989                }
 6990            } else {
 6991                false
 6992            }
 6993        });
 6994        self.metadata_changed(cx);
 6995    }
 6996
 6997    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
 6998        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
 6999        cx.subscribe(worktree, |this, worktree, event, cx| {
 7000            let is_local = worktree.read(cx).is_local();
 7001            match event {
 7002                worktree::Event::UpdatedEntries(changes) => {
 7003                    if is_local {
 7004                        this.update_local_worktree_buffers(&worktree, changes, cx);
 7005                        this.update_local_worktree_language_servers(&worktree, changes, cx);
 7006                        this.update_local_worktree_settings(&worktree, changes, cx);
 7007                        this.update_prettier_settings(&worktree, changes, cx);
 7008                    }
 7009
 7010                    cx.emit(Event::WorktreeUpdatedEntries(
 7011                        worktree.read(cx).id(),
 7012                        changes.clone(),
 7013                    ));
 7014                }
 7015                worktree::Event::UpdatedGitRepositories(updated_repos) => {
 7016                    if is_local {
 7017                        this.update_local_worktree_buffers_git_repos(
 7018                            worktree.clone(),
 7019                            updated_repos,
 7020                            cx,
 7021                        )
 7022                    }
 7023                    cx.emit(Event::WorktreeUpdatedGitRepositories);
 7024                }
 7025            }
 7026        })
 7027        .detach();
 7028
 7029        let push_strong_handle = {
 7030            let worktree = worktree.read(cx);
 7031            self.is_shared() || worktree.is_visible() || worktree.is_remote()
 7032        };
 7033        if push_strong_handle {
 7034            self.worktrees
 7035                .push(WorktreeHandle::Strong(worktree.clone()));
 7036        } else {
 7037            self.worktrees
 7038                .push(WorktreeHandle::Weak(worktree.downgrade()));
 7039        }
 7040
 7041        let handle_id = worktree.entity_id();
 7042        cx.observe_release(worktree, move |this, worktree, cx| {
 7043            let _ = this.remove_worktree(worktree.id(), cx);
 7044            cx.update_global::<SettingsStore, _>(|store, cx| {
 7045                store
 7046                    .clear_local_settings(handle_id.as_u64() as usize, cx)
 7047                    .log_err()
 7048            });
 7049        })
 7050        .detach();
 7051
 7052        cx.emit(Event::WorktreeAdded);
 7053        self.metadata_changed(cx);
 7054    }
 7055
 7056    fn update_local_worktree_buffers(
 7057        &mut self,
 7058        worktree_handle: &Model<Worktree>,
 7059        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 7060        cx: &mut ModelContext<Self>,
 7061    ) {
 7062        let snapshot = worktree_handle.read(cx).snapshot();
 7063
 7064        let mut renamed_buffers = Vec::new();
 7065        for (path, entry_id, _) in changes {
 7066            let worktree_id = worktree_handle.read(cx).id();
 7067            let project_path = ProjectPath {
 7068                worktree_id,
 7069                path: path.clone(),
 7070            };
 7071
 7072            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
 7073                Some(&buffer_id) => buffer_id,
 7074                None => match self.local_buffer_ids_by_path.get(&project_path) {
 7075                    Some(&buffer_id) => buffer_id,
 7076                    None => {
 7077                        continue;
 7078                    }
 7079                },
 7080            };
 7081
 7082            let open_buffer = self.opened_buffers.get(&buffer_id);
 7083            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
 7084                buffer
 7085            } else {
 7086                self.opened_buffers.remove(&buffer_id);
 7087                self.local_buffer_ids_by_path.remove(&project_path);
 7088                self.local_buffer_ids_by_entry_id.remove(entry_id);
 7089                continue;
 7090            };
 7091
 7092            buffer.update(cx, |buffer, cx| {
 7093                if let Some(old_file) = File::from_dyn(buffer.file()) {
 7094                    if old_file.worktree != *worktree_handle {
 7095                        return;
 7096                    }
 7097
 7098                    let new_file = if let Some(entry) = old_file
 7099                        .entry_id
 7100                        .and_then(|entry_id| snapshot.entry_for_id(entry_id))
 7101                    {
 7102                        File {
 7103                            is_local: true,
 7104                            entry_id: Some(entry.id),
 7105                            mtime: entry.mtime,
 7106                            path: entry.path.clone(),
 7107                            worktree: worktree_handle.clone(),
 7108                            is_deleted: false,
 7109                            is_private: entry.is_private,
 7110                        }
 7111                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
 7112                        File {
 7113                            is_local: true,
 7114                            entry_id: Some(entry.id),
 7115                            mtime: entry.mtime,
 7116                            path: entry.path.clone(),
 7117                            worktree: worktree_handle.clone(),
 7118                            is_deleted: false,
 7119                            is_private: entry.is_private,
 7120                        }
 7121                    } else {
 7122                        File {
 7123                            is_local: true,
 7124                            entry_id: old_file.entry_id,
 7125                            path: old_file.path().clone(),
 7126                            mtime: old_file.mtime(),
 7127                            worktree: worktree_handle.clone(),
 7128                            is_deleted: true,
 7129                            is_private: old_file.is_private,
 7130                        }
 7131                    };
 7132
 7133                    let old_path = old_file.abs_path(cx);
 7134                    if new_file.abs_path(cx) != old_path {
 7135                        renamed_buffers.push((cx.handle(), old_file.clone()));
 7136                        self.local_buffer_ids_by_path.remove(&project_path);
 7137                        self.local_buffer_ids_by_path.insert(
 7138                            ProjectPath {
 7139                                worktree_id,
 7140                                path: path.clone(),
 7141                            },
 7142                            buffer_id,
 7143                        );
 7144                    }
 7145
 7146                    if new_file.entry_id != Some(*entry_id) {
 7147                        self.local_buffer_ids_by_entry_id.remove(entry_id);
 7148                        if let Some(entry_id) = new_file.entry_id {
 7149                            self.local_buffer_ids_by_entry_id
 7150                                .insert(entry_id, buffer_id);
 7151                        }
 7152                    }
 7153
 7154                    if new_file != *old_file {
 7155                        if let Some(project_id) = self.remote_id() {
 7156                            self.client
 7157                                .send(proto::UpdateBufferFile {
 7158                                    project_id,
 7159                                    buffer_id: buffer_id.into(),
 7160                                    file: Some(new_file.to_proto()),
 7161                                })
 7162                                .log_err();
 7163                        }
 7164
 7165                        buffer.file_updated(Arc::new(new_file), cx);
 7166                    }
 7167                }
 7168            });
 7169        }
 7170
 7171        for (buffer, old_file) in renamed_buffers {
 7172            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
 7173            self.detect_language_for_buffer(&buffer, cx);
 7174            self.register_buffer_with_language_servers(&buffer, cx);
 7175        }
 7176    }
 7177
 7178    fn update_local_worktree_language_servers(
 7179        &mut self,
 7180        worktree_handle: &Model<Worktree>,
 7181        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 7182        cx: &mut ModelContext<Self>,
 7183    ) {
 7184        if changes.is_empty() {
 7185            return;
 7186        }
 7187
 7188        let worktree_id = worktree_handle.read(cx).id();
 7189        let mut language_server_ids = self
 7190            .language_server_ids
 7191            .iter()
 7192            .filter_map(|((server_worktree_id, _), server_id)| {
 7193                (*server_worktree_id == worktree_id).then_some(*server_id)
 7194            })
 7195            .collect::<Vec<_>>();
 7196        language_server_ids.sort();
 7197        language_server_ids.dedup();
 7198
 7199        let abs_path = worktree_handle.read(cx).abs_path();
 7200        for server_id in &language_server_ids {
 7201            if let Some(LanguageServerState::Running { server, .. }) =
 7202                self.language_servers.get(server_id)
 7203            {
 7204                if let Some(watched_paths) = self
 7205                    .language_server_watched_paths
 7206                    .get(&server_id)
 7207                    .and_then(|paths| paths.get(&worktree_id))
 7208                {
 7209                    let params = lsp::DidChangeWatchedFilesParams {
 7210                        changes: changes
 7211                            .iter()
 7212                            .filter_map(|(path, _, change)| {
 7213                                if !watched_paths.is_match(&path) {
 7214                                    return None;
 7215                                }
 7216                                let typ = match change {
 7217                                    PathChange::Loaded => return None,
 7218                                    PathChange::Added => lsp::FileChangeType::CREATED,
 7219                                    PathChange::Removed => lsp::FileChangeType::DELETED,
 7220                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
 7221                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
 7222                                };
 7223                                Some(lsp::FileEvent {
 7224                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
 7225                                    typ,
 7226                                })
 7227                            })
 7228                            .collect(),
 7229                    };
 7230                    if !params.changes.is_empty() {
 7231                        server
 7232                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
 7233                            .log_err();
 7234                    }
 7235                }
 7236            }
 7237        }
 7238    }
 7239
 7240    fn update_local_worktree_buffers_git_repos(
 7241        &mut self,
 7242        worktree_handle: Model<Worktree>,
 7243        changed_repos: &UpdatedGitRepositoriesSet,
 7244        cx: &mut ModelContext<Self>,
 7245    ) {
 7246        debug_assert!(worktree_handle.read(cx).is_local());
 7247
 7248        // Identify the loading buffers whose containing repository that has changed.
 7249        let future_buffers = self
 7250            .loading_buffers_by_path
 7251            .iter()
 7252            .filter_map(|(project_path, receiver)| {
 7253                if project_path.worktree_id != worktree_handle.read(cx).id() {
 7254                    return None;
 7255                }
 7256                let path = &project_path.path;
 7257                changed_repos
 7258                    .iter()
 7259                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
 7260                let receiver = receiver.clone();
 7261                let path = path.clone();
 7262                let abs_path = worktree_handle.read(cx).absolutize(&path).ok()?;
 7263                Some(async move {
 7264                    wait_for_loading_buffer(receiver)
 7265                        .await
 7266                        .ok()
 7267                        .map(|buffer| (buffer, path, abs_path))
 7268                })
 7269            })
 7270            .collect::<FuturesUnordered<_>>();
 7271
 7272        // Identify the current buffers whose containing repository has changed.
 7273        let current_buffers = self
 7274            .opened_buffers
 7275            .values()
 7276            .filter_map(|buffer| {
 7277                let buffer = buffer.upgrade()?;
 7278                let file = File::from_dyn(buffer.read(cx).file())?;
 7279                if file.worktree != worktree_handle {
 7280                    return None;
 7281                }
 7282                let path = file.path();
 7283                changed_repos
 7284                    .iter()
 7285                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
 7286                Some((buffer, path.clone(), file.abs_path(cx)))
 7287            })
 7288            .collect::<Vec<_>>();
 7289
 7290        if future_buffers.len() + current_buffers.len() == 0 {
 7291            return;
 7292        }
 7293
 7294        let remote_id = self.remote_id();
 7295        let client = self.client.clone();
 7296        let fs = self.fs.clone();
 7297        cx.spawn(move |_, mut cx| async move {
 7298            // Wait for all of the buffers to load.
 7299            let future_buffers = future_buffers.collect::<Vec<_>>().await;
 7300
 7301            // Reload the diff base for every buffer whose containing git repository has changed.
 7302            let snapshot =
 7303                worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
 7304            let diff_bases_by_buffer = cx
 7305                .background_executor()
 7306                .spawn(async move {
 7307                    let mut diff_base_tasks = future_buffers
 7308                        .into_iter()
 7309                        .flatten()
 7310                        .chain(current_buffers)
 7311                        .filter_map(|(buffer, path, abs_path)| {
 7312                            let (work_directory, repo) =
 7313                                snapshot.repository_and_work_directory_for_path(&path)?;
 7314                            let repo_entry = snapshot.get_local_repo(&repo)?;
 7315                            Some((buffer, path, abs_path, work_directory, repo_entry))
 7316                        })
 7317                        .map(|(buffer, path, abs_path, work_directory, repo_entry)| {
 7318                            let fs = fs.clone();
 7319                            async move {
 7320                                let abs_path_metadata = fs
 7321                                    .metadata(&abs_path)
 7322                                    .await
 7323                                    .with_context(|| {
 7324                                        format!("loading file and FS metadata for {path:?}")
 7325                                    })
 7326                                    .log_err()
 7327                                    .flatten()?;
 7328                                let base_text = if abs_path_metadata.is_dir
 7329                                    || abs_path_metadata.is_symlink
 7330                                {
 7331                                    None
 7332                                } else {
 7333                                    let relative_path = path.strip_prefix(&work_directory).ok()?;
 7334                                    repo_entry.repo().lock().load_index_text(relative_path)
 7335                                };
 7336                                Some((buffer, base_text))
 7337                            }
 7338                        })
 7339                        .collect::<FuturesUnordered<_>>();
 7340
 7341                    let mut diff_bases = Vec::with_capacity(diff_base_tasks.len());
 7342                    while let Some(diff_base) = diff_base_tasks.next().await {
 7343                        if let Some(diff_base) = diff_base {
 7344                            diff_bases.push(diff_base);
 7345                        }
 7346                    }
 7347                    diff_bases
 7348                })
 7349                .await;
 7350
 7351            // Assign the new diff bases on all of the buffers.
 7352            for (buffer, diff_base) in diff_bases_by_buffer {
 7353                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
 7354                    buffer.set_diff_base(diff_base.clone(), cx);
 7355                    buffer.remote_id().into()
 7356                })?;
 7357                if let Some(project_id) = remote_id {
 7358                    client
 7359                        .send(proto::UpdateDiffBase {
 7360                            project_id,
 7361                            buffer_id,
 7362                            diff_base,
 7363                        })
 7364                        .log_err();
 7365                }
 7366            }
 7367
 7368            anyhow::Ok(())
 7369        })
 7370        .detach();
 7371    }
 7372
 7373    fn update_local_worktree_settings(
 7374        &mut self,
 7375        worktree: &Model<Worktree>,
 7376        changes: &UpdatedEntriesSet,
 7377        cx: &mut ModelContext<Self>,
 7378    ) {
 7379        if worktree.read(cx).as_local().is_none() {
 7380            return;
 7381        }
 7382        let project_id = self.remote_id();
 7383        let worktree_id = worktree.entity_id();
 7384        let remote_worktree_id = worktree.read(cx).id();
 7385
 7386        let mut settings_contents = Vec::new();
 7387        for (path, _, change) in changes.iter() {
 7388            let removed = change == &PathChange::Removed;
 7389            let abs_path = match worktree.read(cx).absolutize(path) {
 7390                Ok(abs_path) => abs_path,
 7391                Err(e) => {
 7392                    log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
 7393                    continue;
 7394                }
 7395            };
 7396
 7397            if abs_path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
 7398                let settings_dir = Arc::from(
 7399                    path.ancestors()
 7400                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
 7401                        .unwrap(),
 7402                );
 7403                let fs = self.fs.clone();
 7404                settings_contents.push(async move {
 7405                    (
 7406                        settings_dir,
 7407                        if removed {
 7408                            None
 7409                        } else {
 7410                            Some(async move { fs.load(&abs_path).await }.await)
 7411                        },
 7412                    )
 7413                });
 7414            } else if abs_path.ends_with(&*LOCAL_TASKS_RELATIVE_PATH) {
 7415                self.task_inventory().update(cx, |task_inventory, cx| {
 7416                    if removed {
 7417                        task_inventory.remove_local_static_source(&abs_path);
 7418                    } else {
 7419                        let fs = self.fs.clone();
 7420                        let task_abs_path = abs_path.clone();
 7421                        task_inventory.add_source(
 7422                            TaskSourceKind::Worktree {
 7423                                id: remote_worktree_id,
 7424                                abs_path,
 7425                            },
 7426                            |cx| {
 7427                                let tasks_file_rx =
 7428                                    watch_config_file(&cx.background_executor(), fs, task_abs_path);
 7429                                StaticSource::new(
 7430                                    format!("local_tasks_for_workspace_{remote_worktree_id}"),
 7431                                    TrackedFile::new(tasks_file_rx, cx),
 7432                                    cx,
 7433                                )
 7434                            },
 7435                            cx,
 7436                        );
 7437                    }
 7438                })
 7439            } else if abs_path.ends_with(&*LOCAL_VSCODE_TASKS_RELATIVE_PATH) {
 7440                self.task_inventory().update(cx, |task_inventory, cx| {
 7441                    if removed {
 7442                        task_inventory.remove_local_static_source(&abs_path);
 7443                    } else {
 7444                        let fs = self.fs.clone();
 7445                        let task_abs_path = abs_path.clone();
 7446                        task_inventory.add_source(
 7447                            TaskSourceKind::Worktree {
 7448                                id: remote_worktree_id,
 7449                                abs_path,
 7450                            },
 7451                            |cx| {
 7452                                let tasks_file_rx =
 7453                                    watch_config_file(&cx.background_executor(), fs, task_abs_path);
 7454                                StaticSource::new(
 7455                                    format!(
 7456                                        "local_vscode_tasks_for_workspace_{remote_worktree_id}"
 7457                                    ),
 7458                                    TrackedFile::new_convertible::<task::VsCodeTaskFile>(
 7459                                        tasks_file_rx,
 7460                                        cx,
 7461                                    ),
 7462                                    cx,
 7463                                )
 7464                            },
 7465                            cx,
 7466                        );
 7467                    }
 7468                })
 7469            }
 7470        }
 7471
 7472        if settings_contents.is_empty() {
 7473            return;
 7474        }
 7475
 7476        let client = self.client.clone();
 7477        cx.spawn(move |_, cx| async move {
 7478            let settings_contents: Vec<(Arc<Path>, _)> =
 7479                futures::future::join_all(settings_contents).await;
 7480            cx.update(|cx| {
 7481                cx.update_global::<SettingsStore, _>(|store, cx| {
 7482                    for (directory, file_content) in settings_contents {
 7483                        let file_content = file_content.and_then(|content| content.log_err());
 7484                        store
 7485                            .set_local_settings(
 7486                                worktree_id.as_u64() as usize,
 7487                                directory.clone(),
 7488                                file_content.as_deref(),
 7489                                cx,
 7490                            )
 7491                            .log_err();
 7492                        if let Some(remote_id) = project_id {
 7493                            client
 7494                                .send(proto::UpdateWorktreeSettings {
 7495                                    project_id: remote_id,
 7496                                    worktree_id: remote_worktree_id.to_proto(),
 7497                                    path: directory.to_string_lossy().into_owned(),
 7498                                    content: file_content,
 7499                                })
 7500                                .log_err();
 7501                        }
 7502                    }
 7503                });
 7504            })
 7505            .ok();
 7506        })
 7507        .detach();
 7508    }
 7509
 7510    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
 7511        let new_active_entry = entry.and_then(|project_path| {
 7512            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 7513            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
 7514            Some(entry.id)
 7515        });
 7516        if new_active_entry != self.active_entry {
 7517            self.active_entry = new_active_entry;
 7518            cx.emit(Event::ActiveEntryChanged(new_active_entry));
 7519        }
 7520    }
 7521
 7522    pub fn language_servers_running_disk_based_diagnostics(
 7523        &self,
 7524    ) -> impl Iterator<Item = LanguageServerId> + '_ {
 7525        self.language_server_statuses
 7526            .iter()
 7527            .filter_map(|(id, status)| {
 7528                if status.has_pending_diagnostic_updates {
 7529                    Some(*id)
 7530                } else {
 7531                    None
 7532                }
 7533            })
 7534    }
 7535
 7536    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
 7537        let mut summary = DiagnosticSummary::default();
 7538        for (_, _, path_summary) in
 7539            self.diagnostic_summaries(include_ignored, cx)
 7540                .filter(|(path, _, _)| {
 7541                    let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
 7542                    include_ignored || worktree == Some(false)
 7543                })
 7544        {
 7545            summary.error_count += path_summary.error_count;
 7546            summary.warning_count += path_summary.warning_count;
 7547        }
 7548        summary
 7549    }
 7550
 7551    pub fn diagnostic_summaries<'a>(
 7552        &'a self,
 7553        include_ignored: bool,
 7554        cx: &'a AppContext,
 7555    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
 7556        self.visible_worktrees(cx)
 7557            .flat_map(move |worktree| {
 7558                let worktree = worktree.read(cx);
 7559                let worktree_id = worktree.id();
 7560                worktree
 7561                    .diagnostic_summaries()
 7562                    .map(move |(path, server_id, summary)| {
 7563                        (ProjectPath { worktree_id, path }, server_id, summary)
 7564                    })
 7565            })
 7566            .filter(move |(path, _, _)| {
 7567                let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
 7568                include_ignored || worktree == Some(false)
 7569            })
 7570    }
 7571
 7572    pub fn disk_based_diagnostics_started(
 7573        &mut self,
 7574        language_server_id: LanguageServerId,
 7575        cx: &mut ModelContext<Self>,
 7576    ) {
 7577        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
 7578    }
 7579
 7580    pub fn disk_based_diagnostics_finished(
 7581        &mut self,
 7582        language_server_id: LanguageServerId,
 7583        cx: &mut ModelContext<Self>,
 7584    ) {
 7585        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
 7586    }
 7587
 7588    pub fn active_entry(&self) -> Option<ProjectEntryId> {
 7589        self.active_entry
 7590    }
 7591
 7592    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
 7593        self.worktree_for_id(path.worktree_id, cx)?
 7594            .read(cx)
 7595            .entry_for_path(&path.path)
 7596            .cloned()
 7597    }
 7598
 7599    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
 7600        let worktree = self.worktree_for_entry(entry_id, cx)?;
 7601        let worktree = worktree.read(cx);
 7602        let worktree_id = worktree.id();
 7603        let path = worktree.entry_for_id(entry_id)?.path.clone();
 7604        Some(ProjectPath { worktree_id, path })
 7605    }
 7606
 7607    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
 7608        let workspace_root = self
 7609            .worktree_for_id(project_path.worktree_id, cx)?
 7610            .read(cx)
 7611            .abs_path();
 7612        let project_path = project_path.path.as_ref();
 7613
 7614        Some(if project_path == Path::new("") {
 7615            workspace_root.to_path_buf()
 7616        } else {
 7617            workspace_root.join(project_path)
 7618        })
 7619    }
 7620
 7621    pub fn get_workspace_root(
 7622        &self,
 7623        project_path: &ProjectPath,
 7624        cx: &AppContext,
 7625    ) -> Option<PathBuf> {
 7626        Some(
 7627            self.worktree_for_id(project_path.worktree_id, cx)?
 7628                .read(cx)
 7629                .abs_path()
 7630                .to_path_buf(),
 7631        )
 7632    }
 7633
 7634    pub fn get_repo(
 7635        &self,
 7636        project_path: &ProjectPath,
 7637        cx: &AppContext,
 7638    ) -> Option<Arc<Mutex<dyn GitRepository>>> {
 7639        self.worktree_for_id(project_path.worktree_id, cx)?
 7640            .read(cx)
 7641            .as_local()?
 7642            .snapshot()
 7643            .local_git_repo(&project_path.path)
 7644    }
 7645
 7646    pub fn blame_buffer(
 7647        &self,
 7648        buffer: &Model<Buffer>,
 7649        version: Option<clock::Global>,
 7650        cx: &AppContext,
 7651    ) -> Task<Result<Blame>> {
 7652        if self.is_local() {
 7653            let blame_params = maybe!({
 7654                let buffer = buffer.read(cx);
 7655                let buffer_project_path = buffer
 7656                    .project_path(cx)
 7657                    .context("failed to get buffer project path")?;
 7658
 7659                let worktree = self
 7660                    .worktree_for_id(buffer_project_path.worktree_id, cx)
 7661                    .context("failed to get worktree")?
 7662                    .read(cx)
 7663                    .as_local()
 7664                    .context("worktree was not local")?
 7665                    .snapshot();
 7666                let (work_directory, repo) = worktree
 7667                    .repository_and_work_directory_for_path(&buffer_project_path.path)
 7668                    .context("failed to get repo for blamed buffer")?;
 7669
 7670                let repo_entry = worktree
 7671                    .get_local_repo(&repo)
 7672                    .context("failed to get repo for blamed buffer")?;
 7673
 7674                let relative_path = buffer_project_path
 7675                    .path
 7676                    .strip_prefix(&work_directory)?
 7677                    .to_path_buf();
 7678
 7679                let content = match version {
 7680                    Some(version) => buffer.rope_for_version(&version).clone(),
 7681                    None => buffer.as_rope().clone(),
 7682                };
 7683                let repo = repo_entry.repo().clone();
 7684
 7685                anyhow::Ok((repo, relative_path, content))
 7686            });
 7687
 7688            cx.background_executor().spawn(async move {
 7689                let (repo, relative_path, content) = blame_params?;
 7690                let lock = repo.lock();
 7691                lock.blame(&relative_path, content)
 7692            })
 7693        } else {
 7694            let project_id = self.remote_id();
 7695            let buffer_id = buffer.read(cx).remote_id();
 7696            let client = self.client.clone();
 7697            let version = buffer.read(cx).version();
 7698
 7699            cx.spawn(|_| async move {
 7700                let project_id = project_id.context("unable to get project id for buffer")?;
 7701                let response = client
 7702                    .request(proto::BlameBuffer {
 7703                        project_id,
 7704                        buffer_id: buffer_id.into(),
 7705                        version: serialize_version(&version),
 7706                    })
 7707                    .await?;
 7708
 7709                Ok(deserialize_blame_buffer_response(response))
 7710            })
 7711        }
 7712    }
 7713
 7714    // RPC message handlers
 7715
 7716    async fn handle_blame_buffer(
 7717        this: Model<Self>,
 7718        envelope: TypedEnvelope<proto::BlameBuffer>,
 7719        _: Arc<Client>,
 7720        mut cx: AsyncAppContext,
 7721    ) -> Result<proto::BlameBufferResponse> {
 7722        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 7723        let version = deserialize_version(&envelope.payload.version);
 7724
 7725        let buffer = this.update(&mut cx, |this, _cx| {
 7726            this.opened_buffers
 7727                .get(&buffer_id)
 7728                .and_then(|buffer| buffer.upgrade())
 7729                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 7730        })??;
 7731
 7732        buffer
 7733            .update(&mut cx, |buffer, _| {
 7734                buffer.wait_for_version(version.clone())
 7735            })?
 7736            .await?;
 7737
 7738        let blame = this
 7739            .update(&mut cx, |this, cx| {
 7740                this.blame_buffer(&buffer, Some(version), cx)
 7741            })?
 7742            .await?;
 7743
 7744        Ok(serialize_blame_buffer_response(blame))
 7745    }
 7746
 7747    async fn handle_multi_lsp_query(
 7748        project: Model<Self>,
 7749        envelope: TypedEnvelope<proto::MultiLspQuery>,
 7750        _: Arc<Client>,
 7751        mut cx: AsyncAppContext,
 7752    ) -> Result<proto::MultiLspQueryResponse> {
 7753        let sender_id = envelope.original_sender_id()?;
 7754        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 7755        let version = deserialize_version(&envelope.payload.version);
 7756        let buffer = project.update(&mut cx, |project, _cx| {
 7757            project
 7758                .opened_buffers
 7759                .get(&buffer_id)
 7760                .and_then(|buffer| buffer.upgrade())
 7761                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 7762        })??;
 7763        buffer
 7764            .update(&mut cx, |buffer, _| {
 7765                buffer.wait_for_version(version.clone())
 7766            })?
 7767            .await?;
 7768        let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
 7769        match envelope
 7770            .payload
 7771            .strategy
 7772            .context("invalid request without the strategy")?
 7773        {
 7774            proto::multi_lsp_query::Strategy::All(_) => {
 7775                // currently, there's only one multiple language servers query strategy,
 7776                // so just ensure it's specified correctly
 7777            }
 7778        }
 7779        match envelope.payload.request {
 7780            Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
 7781                let get_hover =
 7782                    GetHover::from_proto(get_hover, project.clone(), buffer.clone(), cx.clone())
 7783                        .await?;
 7784                let all_hovers = project
 7785                    .update(&mut cx, |project, cx| {
 7786                        project.request_multiple_lsp_locally(
 7787                            &buffer,
 7788                            Some(get_hover.position),
 7789                            |server_capabilities| match server_capabilities.hover_provider {
 7790                                Some(lsp::HoverProviderCapability::Simple(enabled)) => enabled,
 7791                                Some(lsp::HoverProviderCapability::Options(_)) => true,
 7792                                None => false,
 7793                            },
 7794                            get_hover,
 7795                            cx,
 7796                        )
 7797                    })?
 7798                    .await
 7799                    .into_iter()
 7800                    .filter_map(|hover| remove_empty_hover_blocks(hover?));
 7801                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 7802                    responses: all_hovers
 7803                        .map(|hover| proto::LspResponse {
 7804                            response: Some(proto::lsp_response::Response::GetHoverResponse(
 7805                                GetHover::response_to_proto(
 7806                                    Some(hover),
 7807                                    project,
 7808                                    sender_id,
 7809                                    &buffer_version,
 7810                                    cx,
 7811                                ),
 7812                            )),
 7813                        })
 7814                        .collect(),
 7815                })
 7816            }
 7817            Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
 7818                let get_code_actions = GetCodeActions::from_proto(
 7819                    get_code_actions,
 7820                    project.clone(),
 7821                    buffer.clone(),
 7822                    cx.clone(),
 7823                )
 7824                .await?;
 7825
 7826                let all_actions = project
 7827                    .update(&mut cx, |project, cx| {
 7828                        project.request_multiple_lsp_locally(
 7829                            &buffer,
 7830                            Some(get_code_actions.range.start),
 7831                            GetCodeActions::supports_code_actions,
 7832                            get_code_actions,
 7833                            cx,
 7834                        )
 7835                    })?
 7836                    .await
 7837                    .into_iter();
 7838
 7839                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 7840                    responses: all_actions
 7841                        .map(|code_actions| proto::LspResponse {
 7842                            response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
 7843                                GetCodeActions::response_to_proto(
 7844                                    code_actions,
 7845                                    project,
 7846                                    sender_id,
 7847                                    &buffer_version,
 7848                                    cx,
 7849                                ),
 7850                            )),
 7851                        })
 7852                        .collect(),
 7853                })
 7854            }
 7855            None => anyhow::bail!("empty multi lsp query request"),
 7856        }
 7857    }
 7858
 7859    async fn handle_unshare_project(
 7860        this: Model<Self>,
 7861        _: TypedEnvelope<proto::UnshareProject>,
 7862        _: Arc<Client>,
 7863        mut cx: AsyncAppContext,
 7864    ) -> Result<()> {
 7865        this.update(&mut cx, |this, cx| {
 7866            if this.is_local() {
 7867                this.unshare(cx)?;
 7868            } else {
 7869                this.disconnected_from_host(cx);
 7870            }
 7871            Ok(())
 7872        })?
 7873    }
 7874
 7875    async fn handle_add_collaborator(
 7876        this: Model<Self>,
 7877        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
 7878        _: Arc<Client>,
 7879        mut cx: AsyncAppContext,
 7880    ) -> Result<()> {
 7881        let collaborator = envelope
 7882            .payload
 7883            .collaborator
 7884            .take()
 7885            .ok_or_else(|| anyhow!("empty collaborator"))?;
 7886
 7887        let collaborator = Collaborator::from_proto(collaborator)?;
 7888        this.update(&mut cx, |this, cx| {
 7889            this.shared_buffers.remove(&collaborator.peer_id);
 7890            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
 7891            this.collaborators
 7892                .insert(collaborator.peer_id, collaborator);
 7893            cx.notify();
 7894        })?;
 7895
 7896        Ok(())
 7897    }
 7898
 7899    async fn handle_update_project_collaborator(
 7900        this: Model<Self>,
 7901        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
 7902        _: Arc<Client>,
 7903        mut cx: AsyncAppContext,
 7904    ) -> Result<()> {
 7905        let old_peer_id = envelope
 7906            .payload
 7907            .old_peer_id
 7908            .ok_or_else(|| anyhow!("missing old peer id"))?;
 7909        let new_peer_id = envelope
 7910            .payload
 7911            .new_peer_id
 7912            .ok_or_else(|| anyhow!("missing new peer id"))?;
 7913        this.update(&mut cx, |this, cx| {
 7914            let collaborator = this
 7915                .collaborators
 7916                .remove(&old_peer_id)
 7917                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
 7918            let is_host = collaborator.replica_id == 0;
 7919            this.collaborators.insert(new_peer_id, collaborator);
 7920
 7921            let buffers = this.shared_buffers.remove(&old_peer_id);
 7922            log::info!(
 7923                "peer {} became {}. moving buffers {:?}",
 7924                old_peer_id,
 7925                new_peer_id,
 7926                &buffers
 7927            );
 7928            if let Some(buffers) = buffers {
 7929                this.shared_buffers.insert(new_peer_id, buffers);
 7930            }
 7931
 7932            if is_host {
 7933                this.opened_buffers
 7934                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
 7935                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
 7936                    .unwrap();
 7937            }
 7938
 7939            cx.emit(Event::CollaboratorUpdated {
 7940                old_peer_id,
 7941                new_peer_id,
 7942            });
 7943            cx.notify();
 7944            Ok(())
 7945        })?
 7946    }
 7947
 7948    async fn handle_remove_collaborator(
 7949        this: Model<Self>,
 7950        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
 7951        _: Arc<Client>,
 7952        mut cx: AsyncAppContext,
 7953    ) -> Result<()> {
 7954        this.update(&mut cx, |this, cx| {
 7955            let peer_id = envelope
 7956                .payload
 7957                .peer_id
 7958                .ok_or_else(|| anyhow!("invalid peer id"))?;
 7959            let replica_id = this
 7960                .collaborators
 7961                .remove(&peer_id)
 7962                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
 7963                .replica_id;
 7964            for buffer in this.opened_buffers.values() {
 7965                if let Some(buffer) = buffer.upgrade() {
 7966                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
 7967                }
 7968            }
 7969            this.shared_buffers.remove(&peer_id);
 7970
 7971            cx.emit(Event::CollaboratorLeft(peer_id));
 7972            cx.notify();
 7973            Ok(())
 7974        })?
 7975    }
 7976
 7977    async fn handle_update_project(
 7978        this: Model<Self>,
 7979        envelope: TypedEnvelope<proto::UpdateProject>,
 7980        _: Arc<Client>,
 7981        mut cx: AsyncAppContext,
 7982    ) -> Result<()> {
 7983        this.update(&mut cx, |this, cx| {
 7984            // Don't handle messages that were sent before the response to us joining the project
 7985            if envelope.message_id > this.join_project_response_message_id {
 7986                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
 7987            }
 7988            Ok(())
 7989        })?
 7990    }
 7991
 7992    async fn handle_update_worktree(
 7993        this: Model<Self>,
 7994        envelope: TypedEnvelope<proto::UpdateWorktree>,
 7995        _: Arc<Client>,
 7996        mut cx: AsyncAppContext,
 7997    ) -> Result<()> {
 7998        this.update(&mut cx, |this, cx| {
 7999            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8000            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8001                worktree.update(cx, |worktree, _| {
 8002                    let worktree = worktree.as_remote_mut().unwrap();
 8003                    worktree.update_from_remote(envelope.payload);
 8004                });
 8005            }
 8006            Ok(())
 8007        })?
 8008    }
 8009
 8010    async fn handle_update_worktree_settings(
 8011        this: Model<Self>,
 8012        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
 8013        _: Arc<Client>,
 8014        mut cx: AsyncAppContext,
 8015    ) -> Result<()> {
 8016        this.update(&mut cx, |this, cx| {
 8017            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8018            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8019                cx.update_global::<SettingsStore, _>(|store, cx| {
 8020                    store
 8021                        .set_local_settings(
 8022                            worktree.entity_id().as_u64() as usize,
 8023                            PathBuf::from(&envelope.payload.path).into(),
 8024                            envelope.payload.content.as_deref(),
 8025                            cx,
 8026                        )
 8027                        .log_err();
 8028                });
 8029            }
 8030            Ok(())
 8031        })?
 8032    }
 8033
 8034    async fn handle_create_project_entry(
 8035        this: Model<Self>,
 8036        envelope: TypedEnvelope<proto::CreateProjectEntry>,
 8037        _: Arc<Client>,
 8038        mut cx: AsyncAppContext,
 8039    ) -> Result<proto::ProjectEntryResponse> {
 8040        let worktree = this.update(&mut cx, |this, cx| {
 8041            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8042            this.worktree_for_id(worktree_id, cx)
 8043                .ok_or_else(|| anyhow!("worktree not found"))
 8044        })??;
 8045        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8046        let entry = worktree
 8047            .update(&mut cx, |worktree, cx| {
 8048                let worktree = worktree.as_local_mut().unwrap();
 8049                let path = PathBuf::from(envelope.payload.path);
 8050                worktree.create_entry(path, envelope.payload.is_directory, cx)
 8051            })?
 8052            .await?;
 8053        Ok(proto::ProjectEntryResponse {
 8054            entry: entry.as_ref().map(|e| e.into()),
 8055            worktree_scan_id: worktree_scan_id as u64,
 8056        })
 8057    }
 8058
 8059    async fn handle_rename_project_entry(
 8060        this: Model<Self>,
 8061        envelope: TypedEnvelope<proto::RenameProjectEntry>,
 8062        _: Arc<Client>,
 8063        mut cx: AsyncAppContext,
 8064    ) -> Result<proto::ProjectEntryResponse> {
 8065        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8066        let worktree = this.update(&mut cx, |this, cx| {
 8067            this.worktree_for_entry(entry_id, cx)
 8068                .ok_or_else(|| anyhow!("worktree not found"))
 8069        })??;
 8070        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8071        let entry = worktree
 8072            .update(&mut cx, |worktree, cx| {
 8073                let new_path = PathBuf::from(envelope.payload.new_path);
 8074                worktree
 8075                    .as_local_mut()
 8076                    .unwrap()
 8077                    .rename_entry(entry_id, new_path, cx)
 8078            })?
 8079            .await?;
 8080        Ok(proto::ProjectEntryResponse {
 8081            entry: entry.as_ref().map(|e| e.into()),
 8082            worktree_scan_id: worktree_scan_id as u64,
 8083        })
 8084    }
 8085
 8086    async fn handle_copy_project_entry(
 8087        this: Model<Self>,
 8088        envelope: TypedEnvelope<proto::CopyProjectEntry>,
 8089        _: Arc<Client>,
 8090        mut cx: AsyncAppContext,
 8091    ) -> Result<proto::ProjectEntryResponse> {
 8092        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8093        let worktree = this.update(&mut cx, |this, cx| {
 8094            this.worktree_for_entry(entry_id, cx)
 8095                .ok_or_else(|| anyhow!("worktree not found"))
 8096        })??;
 8097        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8098        let entry = worktree
 8099            .update(&mut cx, |worktree, cx| {
 8100                let new_path = PathBuf::from(envelope.payload.new_path);
 8101                worktree
 8102                    .as_local_mut()
 8103                    .unwrap()
 8104                    .copy_entry(entry_id, new_path, cx)
 8105            })?
 8106            .await?;
 8107        Ok(proto::ProjectEntryResponse {
 8108            entry: entry.as_ref().map(|e| e.into()),
 8109            worktree_scan_id: worktree_scan_id as u64,
 8110        })
 8111    }
 8112
 8113    async fn handle_delete_project_entry(
 8114        this: Model<Self>,
 8115        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
 8116        _: Arc<Client>,
 8117        mut cx: AsyncAppContext,
 8118    ) -> Result<proto::ProjectEntryResponse> {
 8119        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8120
 8121        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
 8122
 8123        let worktree = this.update(&mut cx, |this, cx| {
 8124            this.worktree_for_entry(entry_id, cx)
 8125                .ok_or_else(|| anyhow!("worktree not found"))
 8126        })??;
 8127        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
 8128        worktree
 8129            .update(&mut cx, |worktree, cx| {
 8130                worktree
 8131                    .as_local_mut()
 8132                    .unwrap()
 8133                    .delete_entry(entry_id, cx)
 8134                    .ok_or_else(|| anyhow!("invalid entry"))
 8135            })??
 8136            .await?;
 8137        Ok(proto::ProjectEntryResponse {
 8138            entry: None,
 8139            worktree_scan_id: worktree_scan_id as u64,
 8140        })
 8141    }
 8142
 8143    async fn handle_expand_project_entry(
 8144        this: Model<Self>,
 8145        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
 8146        _: Arc<Client>,
 8147        mut cx: AsyncAppContext,
 8148    ) -> Result<proto::ExpandProjectEntryResponse> {
 8149        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 8150        let worktree = this
 8151            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
 8152            .ok_or_else(|| anyhow!("invalid request"))?;
 8153        worktree
 8154            .update(&mut cx, |worktree, cx| {
 8155                worktree
 8156                    .as_local_mut()
 8157                    .unwrap()
 8158                    .expand_entry(entry_id, cx)
 8159                    .ok_or_else(|| anyhow!("invalid entry"))
 8160            })??
 8161            .await?;
 8162        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
 8163        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
 8164    }
 8165
 8166    async fn handle_update_diagnostic_summary(
 8167        this: Model<Self>,
 8168        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 8169        _: Arc<Client>,
 8170        mut cx: AsyncAppContext,
 8171    ) -> Result<()> {
 8172        this.update(&mut cx, |this, cx| {
 8173            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8174            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8175                if let Some(summary) = envelope.payload.summary {
 8176                    let project_path = ProjectPath {
 8177                        worktree_id,
 8178                        path: Path::new(&summary.path).into(),
 8179                    };
 8180                    worktree.update(cx, |worktree, _| {
 8181                        worktree
 8182                            .as_remote_mut()
 8183                            .unwrap()
 8184                            .update_diagnostic_summary(project_path.path.clone(), &summary);
 8185                    });
 8186                    cx.emit(Event::DiagnosticsUpdated {
 8187                        language_server_id: LanguageServerId(summary.language_server_id as usize),
 8188                        path: project_path,
 8189                    });
 8190                }
 8191            }
 8192            Ok(())
 8193        })?
 8194    }
 8195
 8196    async fn handle_start_language_server(
 8197        this: Model<Self>,
 8198        envelope: TypedEnvelope<proto::StartLanguageServer>,
 8199        _: Arc<Client>,
 8200        mut cx: AsyncAppContext,
 8201    ) -> Result<()> {
 8202        let server = envelope
 8203            .payload
 8204            .server
 8205            .ok_or_else(|| anyhow!("invalid server"))?;
 8206        this.update(&mut cx, |this, cx| {
 8207            this.language_server_statuses.insert(
 8208                LanguageServerId(server.id as usize),
 8209                LanguageServerStatus {
 8210                    name: server.name,
 8211                    pending_work: Default::default(),
 8212                    has_pending_diagnostic_updates: false,
 8213                    progress_tokens: Default::default(),
 8214                },
 8215            );
 8216            cx.notify();
 8217        })?;
 8218        Ok(())
 8219    }
 8220
 8221    async fn handle_update_language_server(
 8222        this: Model<Self>,
 8223        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
 8224        _: Arc<Client>,
 8225        mut cx: AsyncAppContext,
 8226    ) -> Result<()> {
 8227        this.update(&mut cx, |this, cx| {
 8228            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 8229
 8230            match envelope
 8231                .payload
 8232                .variant
 8233                .ok_or_else(|| anyhow!("invalid variant"))?
 8234            {
 8235                proto::update_language_server::Variant::WorkStart(payload) => {
 8236                    this.on_lsp_work_start(
 8237                        language_server_id,
 8238                        payload.token,
 8239                        LanguageServerProgress {
 8240                            message: payload.message,
 8241                            percentage: payload.percentage.map(|p| p as usize),
 8242                            last_update_at: Instant::now(),
 8243                        },
 8244                        cx,
 8245                    );
 8246                }
 8247
 8248                proto::update_language_server::Variant::WorkProgress(payload) => {
 8249                    this.on_lsp_work_progress(
 8250                        language_server_id,
 8251                        payload.token,
 8252                        LanguageServerProgress {
 8253                            message: payload.message,
 8254                            percentage: payload.percentage.map(|p| p as usize),
 8255                            last_update_at: Instant::now(),
 8256                        },
 8257                        cx,
 8258                    );
 8259                }
 8260
 8261                proto::update_language_server::Variant::WorkEnd(payload) => {
 8262                    this.on_lsp_work_end(language_server_id, payload.token, cx);
 8263                }
 8264
 8265                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
 8266                    this.disk_based_diagnostics_started(language_server_id, cx);
 8267                }
 8268
 8269                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
 8270                    this.disk_based_diagnostics_finished(language_server_id, cx)
 8271                }
 8272            }
 8273
 8274            Ok(())
 8275        })?
 8276    }
 8277
 8278    async fn handle_update_buffer(
 8279        this: Model<Self>,
 8280        envelope: TypedEnvelope<proto::UpdateBuffer>,
 8281        _: Arc<Client>,
 8282        mut cx: AsyncAppContext,
 8283    ) -> Result<proto::Ack> {
 8284        this.update(&mut cx, |this, cx| {
 8285            let payload = envelope.payload.clone();
 8286            let buffer_id = BufferId::new(payload.buffer_id)?;
 8287            let ops = payload
 8288                .operations
 8289                .into_iter()
 8290                .map(language::proto::deserialize_operation)
 8291                .collect::<Result<Vec<_>, _>>()?;
 8292            let is_remote = this.is_remote();
 8293            match this.opened_buffers.entry(buffer_id) {
 8294                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
 8295                    OpenBuffer::Strong(buffer) => {
 8296                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
 8297                    }
 8298                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
 8299                    OpenBuffer::Weak(_) => {}
 8300                },
 8301                hash_map::Entry::Vacant(e) => {
 8302                    assert!(
 8303                        is_remote,
 8304                        "received buffer update from {:?}",
 8305                        envelope.original_sender_id
 8306                    );
 8307                    e.insert(OpenBuffer::Operations(ops));
 8308                }
 8309            }
 8310            Ok(proto::Ack {})
 8311        })?
 8312    }
 8313
 8314    async fn handle_create_buffer_for_peer(
 8315        this: Model<Self>,
 8316        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
 8317        _: Arc<Client>,
 8318        mut cx: AsyncAppContext,
 8319    ) -> Result<()> {
 8320        this.update(&mut cx, |this, cx| {
 8321            match envelope
 8322                .payload
 8323                .variant
 8324                .ok_or_else(|| anyhow!("missing variant"))?
 8325            {
 8326                proto::create_buffer_for_peer::Variant::State(mut state) => {
 8327                    let buffer_id = BufferId::new(state.id)?;
 8328
 8329                    let buffer_result = maybe!({
 8330                        let mut buffer_file = None;
 8331                        if let Some(file) = state.file.take() {
 8332                            let worktree_id = WorktreeId::from_proto(file.worktree_id);
 8333                            let worktree =
 8334                                this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
 8335                                    anyhow!("no worktree found for id {}", file.worktree_id)
 8336                                })?;
 8337                            buffer_file =
 8338                                Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
 8339                                    as Arc<dyn language::File>);
 8340                        }
 8341                        Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
 8342                    });
 8343
 8344                    match buffer_result {
 8345                        Ok(buffer) => {
 8346                            let buffer = cx.new_model(|_| buffer);
 8347                            this.incomplete_remote_buffers.insert(buffer_id, buffer);
 8348                        }
 8349                        Err(error) => {
 8350                            if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
 8351                                for listener in listeners {
 8352                                    listener.send(Err(anyhow!(error.cloned()))).ok();
 8353                                }
 8354                            }
 8355                        }
 8356                    };
 8357                }
 8358                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
 8359                    let buffer_id = BufferId::new(chunk.buffer_id)?;
 8360                    let buffer = this
 8361                        .incomplete_remote_buffers
 8362                        .get(&buffer_id)
 8363                        .cloned()
 8364                        .ok_or_else(|| {
 8365                            anyhow!(
 8366                                "received chunk for buffer {} without initial state",
 8367                                chunk.buffer_id
 8368                            )
 8369                        })?;
 8370
 8371                    let result = maybe!({
 8372                        let operations = chunk
 8373                            .operations
 8374                            .into_iter()
 8375                            .map(language::proto::deserialize_operation)
 8376                            .collect::<Result<Vec<_>>>()?;
 8377                        buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))
 8378                    });
 8379
 8380                    if let Err(error) = result {
 8381                        this.incomplete_remote_buffers.remove(&buffer_id);
 8382                        if let Some(listeners) = this.loading_buffers.remove(&buffer_id) {
 8383                            for listener in listeners {
 8384                                listener.send(Err(error.cloned())).ok();
 8385                            }
 8386                        }
 8387                    } else {
 8388                        if chunk.is_last {
 8389                            this.incomplete_remote_buffers.remove(&buffer_id);
 8390                            this.register_buffer(&buffer, cx)?;
 8391                        }
 8392                    }
 8393                }
 8394            }
 8395
 8396            Ok(())
 8397        })?
 8398    }
 8399
 8400    async fn handle_update_diff_base(
 8401        this: Model<Self>,
 8402        envelope: TypedEnvelope<proto::UpdateDiffBase>,
 8403        _: Arc<Client>,
 8404        mut cx: AsyncAppContext,
 8405    ) -> Result<()> {
 8406        this.update(&mut cx, |this, cx| {
 8407            let buffer_id = envelope.payload.buffer_id;
 8408            let buffer_id = BufferId::new(buffer_id)?;
 8409            let diff_base = envelope.payload.diff_base;
 8410            if let Some(buffer) = this
 8411                .opened_buffers
 8412                .get_mut(&buffer_id)
 8413                .and_then(|b| b.upgrade())
 8414                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
 8415            {
 8416                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
 8417            }
 8418            Ok(())
 8419        })?
 8420    }
 8421
 8422    async fn handle_update_buffer_file(
 8423        this: Model<Self>,
 8424        envelope: TypedEnvelope<proto::UpdateBufferFile>,
 8425        _: Arc<Client>,
 8426        mut cx: AsyncAppContext,
 8427    ) -> Result<()> {
 8428        let buffer_id = envelope.payload.buffer_id;
 8429        let buffer_id = BufferId::new(buffer_id)?;
 8430
 8431        this.update(&mut cx, |this, cx| {
 8432            let payload = envelope.payload.clone();
 8433            if let Some(buffer) = this
 8434                .opened_buffers
 8435                .get(&buffer_id)
 8436                .and_then(|b| b.upgrade())
 8437                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned())
 8438            {
 8439                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
 8440                let worktree = this
 8441                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
 8442                    .ok_or_else(|| anyhow!("no such worktree"))?;
 8443                let file = File::from_proto(file, worktree, cx)?;
 8444                buffer.update(cx, |buffer, cx| {
 8445                    buffer.file_updated(Arc::new(file), cx);
 8446                });
 8447                this.detect_language_for_buffer(&buffer, cx);
 8448            }
 8449            Ok(())
 8450        })?
 8451    }
 8452
 8453    async fn handle_save_buffer(
 8454        this: Model<Self>,
 8455        envelope: TypedEnvelope<proto::SaveBuffer>,
 8456        _: Arc<Client>,
 8457        mut cx: AsyncAppContext,
 8458    ) -> Result<proto::BufferSaved> {
 8459        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8460        let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
 8461            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
 8462            let buffer = this
 8463                .opened_buffers
 8464                .get(&buffer_id)
 8465                .and_then(|buffer| buffer.upgrade())
 8466                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 8467            anyhow::Ok((project_id, buffer))
 8468        })??;
 8469        buffer
 8470            .update(&mut cx, |buffer, _| {
 8471                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 8472            })?
 8473            .await?;
 8474        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
 8475
 8476        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
 8477            .await?;
 8478        buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
 8479            project_id,
 8480            buffer_id: buffer_id.into(),
 8481            version: serialize_version(buffer.saved_version()),
 8482            mtime: buffer.saved_mtime().map(|time| time.into()),
 8483            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
 8484        })
 8485    }
 8486
 8487    async fn handle_reload_buffers(
 8488        this: Model<Self>,
 8489        envelope: TypedEnvelope<proto::ReloadBuffers>,
 8490        _: Arc<Client>,
 8491        mut cx: AsyncAppContext,
 8492    ) -> Result<proto::ReloadBuffersResponse> {
 8493        let sender_id = envelope.original_sender_id()?;
 8494        let reload = this.update(&mut cx, |this, cx| {
 8495            let mut buffers = HashSet::default();
 8496            for buffer_id in &envelope.payload.buffer_ids {
 8497                let buffer_id = BufferId::new(*buffer_id)?;
 8498                buffers.insert(
 8499                    this.opened_buffers
 8500                        .get(&buffer_id)
 8501                        .and_then(|buffer| buffer.upgrade())
 8502                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
 8503                );
 8504            }
 8505            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
 8506        })??;
 8507
 8508        let project_transaction = reload.await?;
 8509        let project_transaction = this.update(&mut cx, |this, cx| {
 8510            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 8511        })?;
 8512        Ok(proto::ReloadBuffersResponse {
 8513            transaction: Some(project_transaction),
 8514        })
 8515    }
 8516
 8517    async fn handle_synchronize_buffers(
 8518        this: Model<Self>,
 8519        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
 8520        _: Arc<Client>,
 8521        mut cx: AsyncAppContext,
 8522    ) -> Result<proto::SynchronizeBuffersResponse> {
 8523        let project_id = envelope.payload.project_id;
 8524        let mut response = proto::SynchronizeBuffersResponse {
 8525            buffers: Default::default(),
 8526        };
 8527
 8528        this.update(&mut cx, |this, cx| {
 8529            let Some(guest_id) = envelope.original_sender_id else {
 8530                error!("missing original_sender_id on SynchronizeBuffers request");
 8531                bail!("missing original_sender_id on SynchronizeBuffers request");
 8532            };
 8533
 8534            this.shared_buffers.entry(guest_id).or_default().clear();
 8535            for buffer in envelope.payload.buffers {
 8536                let buffer_id = BufferId::new(buffer.id)?;
 8537                let remote_version = language::proto::deserialize_version(&buffer.version);
 8538                if let Some(buffer) = this.buffer_for_id(buffer_id) {
 8539                    this.shared_buffers
 8540                        .entry(guest_id)
 8541                        .or_default()
 8542                        .insert(buffer_id);
 8543
 8544                    let buffer = buffer.read(cx);
 8545                    response.buffers.push(proto::BufferVersion {
 8546                        id: buffer_id.into(),
 8547                        version: language::proto::serialize_version(&buffer.version),
 8548                    });
 8549
 8550                    let operations = buffer.serialize_ops(Some(remote_version), cx);
 8551                    let client = this.client.clone();
 8552                    if let Some(file) = buffer.file() {
 8553                        client
 8554                            .send(proto::UpdateBufferFile {
 8555                                project_id,
 8556                                buffer_id: buffer_id.into(),
 8557                                file: Some(file.to_proto()),
 8558                            })
 8559                            .log_err();
 8560                    }
 8561
 8562                    client
 8563                        .send(proto::UpdateDiffBase {
 8564                            project_id,
 8565                            buffer_id: buffer_id.into(),
 8566                            diff_base: buffer.diff_base().map(Into::into),
 8567                        })
 8568                        .log_err();
 8569
 8570                    client
 8571                        .send(proto::BufferReloaded {
 8572                            project_id,
 8573                            buffer_id: buffer_id.into(),
 8574                            version: language::proto::serialize_version(buffer.saved_version()),
 8575                            mtime: buffer.saved_mtime().map(|time| time.into()),
 8576                            fingerprint: language::proto::serialize_fingerprint(
 8577                                buffer.saved_version_fingerprint(),
 8578                            ),
 8579                            line_ending: language::proto::serialize_line_ending(
 8580                                buffer.line_ending(),
 8581                            ) as i32,
 8582                        })
 8583                        .log_err();
 8584
 8585                    cx.background_executor()
 8586                        .spawn(
 8587                            async move {
 8588                                let operations = operations.await;
 8589                                for chunk in split_operations(operations) {
 8590                                    client
 8591                                        .request(proto::UpdateBuffer {
 8592                                            project_id,
 8593                                            buffer_id: buffer_id.into(),
 8594                                            operations: chunk,
 8595                                        })
 8596                                        .await?;
 8597                                }
 8598                                anyhow::Ok(())
 8599                            }
 8600                            .log_err(),
 8601                        )
 8602                        .detach();
 8603                }
 8604            }
 8605            Ok(())
 8606        })??;
 8607
 8608        Ok(response)
 8609    }
 8610
 8611    async fn handle_format_buffers(
 8612        this: Model<Self>,
 8613        envelope: TypedEnvelope<proto::FormatBuffers>,
 8614        _: Arc<Client>,
 8615        mut cx: AsyncAppContext,
 8616    ) -> Result<proto::FormatBuffersResponse> {
 8617        let sender_id = envelope.original_sender_id()?;
 8618        let format = this.update(&mut cx, |this, cx| {
 8619            let mut buffers = HashSet::default();
 8620            for buffer_id in &envelope.payload.buffer_ids {
 8621                let buffer_id = BufferId::new(*buffer_id)?;
 8622                buffers.insert(
 8623                    this.opened_buffers
 8624                        .get(&buffer_id)
 8625                        .and_then(|buffer| buffer.upgrade())
 8626                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
 8627                );
 8628            }
 8629            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
 8630            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
 8631        })??;
 8632
 8633        let project_transaction = format.await?;
 8634        let project_transaction = this.update(&mut cx, |this, cx| {
 8635            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 8636        })?;
 8637        Ok(proto::FormatBuffersResponse {
 8638            transaction: Some(project_transaction),
 8639        })
 8640    }
 8641
 8642    async fn handle_apply_additional_edits_for_completion(
 8643        this: Model<Self>,
 8644        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
 8645        _: Arc<Client>,
 8646        mut cx: AsyncAppContext,
 8647    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
 8648        let (buffer, completion) = this.update(&mut cx, |this, _| {
 8649            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8650            let buffer = this
 8651                .opened_buffers
 8652                .get(&buffer_id)
 8653                .and_then(|buffer| buffer.upgrade())
 8654                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 8655            let completion = Self::deserialize_completion(
 8656                envelope
 8657                    .payload
 8658                    .completion
 8659                    .ok_or_else(|| anyhow!("invalid completion"))?,
 8660            )?;
 8661            anyhow::Ok((buffer, completion))
 8662        })??;
 8663
 8664        let apply_additional_edits = this.update(&mut cx, |this, cx| {
 8665            this.apply_additional_edits_for_completion(
 8666                buffer,
 8667                Completion {
 8668                    old_range: completion.old_range,
 8669                    new_text: completion.new_text,
 8670                    lsp_completion: completion.lsp_completion,
 8671                    server_id: completion.server_id,
 8672                    documentation: None,
 8673                    label: CodeLabel {
 8674                        text: Default::default(),
 8675                        runs: Default::default(),
 8676                        filter_range: Default::default(),
 8677                    },
 8678                },
 8679                false,
 8680                cx,
 8681            )
 8682        })?;
 8683
 8684        Ok(proto::ApplyCompletionAdditionalEditsResponse {
 8685            transaction: apply_additional_edits
 8686                .await?
 8687                .as_ref()
 8688                .map(language::proto::serialize_transaction),
 8689        })
 8690    }
 8691
 8692    async fn handle_resolve_completion_documentation(
 8693        this: Model<Self>,
 8694        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
 8695        _: Arc<Client>,
 8696        mut cx: AsyncAppContext,
 8697    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
 8698        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
 8699
 8700        let completion = this
 8701            .read_with(&mut cx, |this, _| {
 8702                let id = LanguageServerId(envelope.payload.language_server_id as usize);
 8703                let Some(server) = this.language_server_for_id(id) else {
 8704                    return Err(anyhow!("No language server {id}"));
 8705                };
 8706
 8707                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
 8708            })??
 8709            .await?;
 8710
 8711        let mut is_markdown = false;
 8712        let text = match completion.documentation {
 8713            Some(lsp::Documentation::String(text)) => text,
 8714
 8715            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
 8716                is_markdown = kind == lsp::MarkupKind::Markdown;
 8717                value
 8718            }
 8719
 8720            _ => String::new(),
 8721        };
 8722
 8723        Ok(proto::ResolveCompletionDocumentationResponse { text, is_markdown })
 8724    }
 8725
 8726    async fn handle_apply_code_action(
 8727        this: Model<Self>,
 8728        envelope: TypedEnvelope<proto::ApplyCodeAction>,
 8729        _: Arc<Client>,
 8730        mut cx: AsyncAppContext,
 8731    ) -> Result<proto::ApplyCodeActionResponse> {
 8732        let sender_id = envelope.original_sender_id()?;
 8733        let action = Self::deserialize_code_action(
 8734            envelope
 8735                .payload
 8736                .action
 8737                .ok_or_else(|| anyhow!("invalid action"))?,
 8738        )?;
 8739        let apply_code_action = this.update(&mut cx, |this, cx| {
 8740            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8741            let buffer = this
 8742                .opened_buffers
 8743                .get(&buffer_id)
 8744                .and_then(|buffer| buffer.upgrade())
 8745                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
 8746            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
 8747        })??;
 8748
 8749        let project_transaction = apply_code_action.await?;
 8750        let project_transaction = this.update(&mut cx, |this, cx| {
 8751            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 8752        })?;
 8753        Ok(proto::ApplyCodeActionResponse {
 8754            transaction: Some(project_transaction),
 8755        })
 8756    }
 8757
 8758    async fn handle_on_type_formatting(
 8759        this: Model<Self>,
 8760        envelope: TypedEnvelope<proto::OnTypeFormatting>,
 8761        _: Arc<Client>,
 8762        mut cx: AsyncAppContext,
 8763    ) -> Result<proto::OnTypeFormattingResponse> {
 8764        let on_type_formatting = this.update(&mut cx, |this, cx| {
 8765            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8766            let buffer = this
 8767                .opened_buffers
 8768                .get(&buffer_id)
 8769                .and_then(|buffer| buffer.upgrade())
 8770                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
 8771            let position = envelope
 8772                .payload
 8773                .position
 8774                .and_then(deserialize_anchor)
 8775                .ok_or_else(|| anyhow!("invalid position"))?;
 8776            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
 8777                buffer,
 8778                position,
 8779                envelope.payload.trigger.clone(),
 8780                cx,
 8781            ))
 8782        })??;
 8783
 8784        let transaction = on_type_formatting
 8785            .await?
 8786            .as_ref()
 8787            .map(language::proto::serialize_transaction);
 8788        Ok(proto::OnTypeFormattingResponse { transaction })
 8789    }
 8790
 8791    async fn handle_inlay_hints(
 8792        this: Model<Self>,
 8793        envelope: TypedEnvelope<proto::InlayHints>,
 8794        _: Arc<Client>,
 8795        mut cx: AsyncAppContext,
 8796    ) -> Result<proto::InlayHintsResponse> {
 8797        let sender_id = envelope.original_sender_id()?;
 8798        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8799        let buffer = this.update(&mut cx, |this, _| {
 8800            this.opened_buffers
 8801                .get(&buffer_id)
 8802                .and_then(|buffer| buffer.upgrade())
 8803                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
 8804        })??;
 8805        buffer
 8806            .update(&mut cx, |buffer, _| {
 8807                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 8808            })?
 8809            .await
 8810            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
 8811
 8812        let start = envelope
 8813            .payload
 8814            .start
 8815            .and_then(deserialize_anchor)
 8816            .context("missing range start")?;
 8817        let end = envelope
 8818            .payload
 8819            .end
 8820            .and_then(deserialize_anchor)
 8821            .context("missing range end")?;
 8822        let buffer_hints = this
 8823            .update(&mut cx, |project, cx| {
 8824                project.inlay_hints(buffer.clone(), start..end, cx)
 8825            })?
 8826            .await
 8827            .context("inlay hints fetch")?;
 8828
 8829        this.update(&mut cx, |project, cx| {
 8830            InlayHints::response_to_proto(
 8831                buffer_hints,
 8832                project,
 8833                sender_id,
 8834                &buffer.read(cx).version(),
 8835                cx,
 8836            )
 8837        })
 8838    }
 8839
 8840    async fn handle_resolve_inlay_hint(
 8841        this: Model<Self>,
 8842        envelope: TypedEnvelope<proto::ResolveInlayHint>,
 8843        _: Arc<Client>,
 8844        mut cx: AsyncAppContext,
 8845    ) -> Result<proto::ResolveInlayHintResponse> {
 8846        let proto_hint = envelope
 8847            .payload
 8848            .hint
 8849            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
 8850        let hint = InlayHints::proto_to_project_hint(proto_hint)
 8851            .context("resolved proto inlay hint conversion")?;
 8852        let buffer = this.update(&mut cx, |this, _cx| {
 8853            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8854            this.opened_buffers
 8855                .get(&buffer_id)
 8856                .and_then(|buffer| buffer.upgrade())
 8857                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 8858        })??;
 8859        let response_hint = this
 8860            .update(&mut cx, |project, cx| {
 8861                project.resolve_inlay_hint(
 8862                    hint,
 8863                    buffer,
 8864                    LanguageServerId(envelope.payload.language_server_id as usize),
 8865                    cx,
 8866                )
 8867            })?
 8868            .await
 8869            .context("inlay hints fetch")?;
 8870        Ok(proto::ResolveInlayHintResponse {
 8871            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
 8872        })
 8873    }
 8874
 8875    async fn try_resolve_code_action(
 8876        lang_server: &LanguageServer,
 8877        action: &mut CodeAction,
 8878    ) -> anyhow::Result<()> {
 8879        if GetCodeActions::can_resolve_actions(&lang_server.capabilities()) {
 8880            if action.lsp_action.data.is_some()
 8881                && (action.lsp_action.command.is_none() || action.lsp_action.edit.is_none())
 8882            {
 8883                action.lsp_action = lang_server
 8884                    .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action.clone())
 8885                    .await?;
 8886            }
 8887        }
 8888
 8889        anyhow::Ok(())
 8890    }
 8891
 8892    async fn execute_code_actions_on_servers(
 8893        project: &WeakModel<Project>,
 8894        adapters_and_servers: &Vec<(Arc<CachedLspAdapter>, Arc<LanguageServer>)>,
 8895        code_actions: Vec<lsp::CodeActionKind>,
 8896        buffer: &Model<Buffer>,
 8897        push_to_history: bool,
 8898        project_transaction: &mut ProjectTransaction,
 8899        cx: &mut AsyncAppContext,
 8900    ) -> Result<(), anyhow::Error> {
 8901        for (lsp_adapter, language_server) in adapters_and_servers.iter() {
 8902            let code_actions = code_actions.clone();
 8903
 8904            let actions = project
 8905                .update(cx, move |this, cx| {
 8906                    let request = GetCodeActions {
 8907                        range: text::Anchor::MIN..text::Anchor::MAX,
 8908                        kinds: Some(code_actions),
 8909                    };
 8910                    let server = LanguageServerToQuery::Other(language_server.server_id());
 8911                    this.request_lsp(buffer.clone(), server, request, cx)
 8912                })?
 8913                .await?;
 8914
 8915            for mut action in actions {
 8916                Self::try_resolve_code_action(&language_server, &mut action)
 8917                    .await
 8918                    .context("resolving a formatting code action")?;
 8919
 8920                if let Some(edit) = action.lsp_action.edit {
 8921                    if edit.changes.is_none() && edit.document_changes.is_none() {
 8922                        continue;
 8923                    }
 8924
 8925                    let new = Self::deserialize_workspace_edit(
 8926                        project
 8927                            .upgrade()
 8928                            .ok_or_else(|| anyhow!("project dropped"))?,
 8929                        edit,
 8930                        push_to_history,
 8931                        lsp_adapter.clone(),
 8932                        language_server.clone(),
 8933                        cx,
 8934                    )
 8935                    .await?;
 8936                    project_transaction.0.extend(new.0);
 8937                }
 8938
 8939                if let Some(command) = action.lsp_action.command {
 8940                    project.update(cx, |this, _| {
 8941                        this.last_workspace_edits_by_language_server
 8942                            .remove(&language_server.server_id());
 8943                    })?;
 8944
 8945                    language_server
 8946                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 8947                            command: command.command,
 8948                            arguments: command.arguments.unwrap_or_default(),
 8949                            ..Default::default()
 8950                        })
 8951                        .await?;
 8952
 8953                    project.update(cx, |this, _| {
 8954                        project_transaction.0.extend(
 8955                            this.last_workspace_edits_by_language_server
 8956                                .remove(&language_server.server_id())
 8957                                .unwrap_or_default()
 8958                                .0,
 8959                        )
 8960                    })?;
 8961                }
 8962            }
 8963        }
 8964
 8965        Ok(())
 8966    }
 8967
 8968    async fn handle_refresh_inlay_hints(
 8969        this: Model<Self>,
 8970        _: TypedEnvelope<proto::RefreshInlayHints>,
 8971        _: Arc<Client>,
 8972        mut cx: AsyncAppContext,
 8973    ) -> Result<proto::Ack> {
 8974        this.update(&mut cx, |_, cx| {
 8975            cx.emit(Event::RefreshInlayHints);
 8976        })?;
 8977        Ok(proto::Ack {})
 8978    }
 8979
 8980    async fn handle_lsp_command<T: LspCommand>(
 8981        this: Model<Self>,
 8982        envelope: TypedEnvelope<T::ProtoRequest>,
 8983        _: Arc<Client>,
 8984        mut cx: AsyncAppContext,
 8985    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
 8986    where
 8987        <T::LspRequest as lsp::request::Request>::Params: Send,
 8988        <T::LspRequest as lsp::request::Request>::Result: Send,
 8989    {
 8990        let sender_id = envelope.original_sender_id()?;
 8991        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
 8992        let buffer_handle = this.update(&mut cx, |this, _cx| {
 8993            this.opened_buffers
 8994                .get(&buffer_id)
 8995                .and_then(|buffer| buffer.upgrade())
 8996                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
 8997        })??;
 8998        let request = T::from_proto(
 8999            envelope.payload,
 9000            this.clone(),
 9001            buffer_handle.clone(),
 9002            cx.clone(),
 9003        )
 9004        .await?;
 9005        let response = this
 9006            .update(&mut cx, |this, cx| {
 9007                this.request_lsp(
 9008                    buffer_handle.clone(),
 9009                    LanguageServerToQuery::Primary,
 9010                    request,
 9011                    cx,
 9012                )
 9013            })?
 9014            .await?;
 9015        this.update(&mut cx, |this, cx| {
 9016            Ok(T::response_to_proto(
 9017                response,
 9018                this,
 9019                sender_id,
 9020                &buffer_handle.read(cx).version(),
 9021                cx,
 9022            ))
 9023        })?
 9024    }
 9025
 9026    async fn handle_get_project_symbols(
 9027        this: Model<Self>,
 9028        envelope: TypedEnvelope<proto::GetProjectSymbols>,
 9029        _: Arc<Client>,
 9030        mut cx: AsyncAppContext,
 9031    ) -> Result<proto::GetProjectSymbolsResponse> {
 9032        let symbols = this
 9033            .update(&mut cx, |this, cx| {
 9034                this.symbols(&envelope.payload.query, cx)
 9035            })?
 9036            .await?;
 9037
 9038        Ok(proto::GetProjectSymbolsResponse {
 9039            symbols: symbols.iter().map(serialize_symbol).collect(),
 9040        })
 9041    }
 9042
 9043    async fn handle_search_project(
 9044        this: Model<Self>,
 9045        envelope: TypedEnvelope<proto::SearchProject>,
 9046        _: Arc<Client>,
 9047        mut cx: AsyncAppContext,
 9048    ) -> Result<proto::SearchProjectResponse> {
 9049        let peer_id = envelope.original_sender_id()?;
 9050        let query = SearchQuery::from_proto(envelope.payload)?;
 9051        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
 9052
 9053        cx.spawn(move |mut cx| async move {
 9054            let mut locations = Vec::new();
 9055            let mut limit_reached = false;
 9056            while let Some(result) = result.next().await {
 9057                match result {
 9058                    SearchResult::Buffer { buffer, ranges } => {
 9059                        for range in ranges {
 9060                            let start = serialize_anchor(&range.start);
 9061                            let end = serialize_anchor(&range.end);
 9062                            let buffer_id = this.update(&mut cx, |this, cx| {
 9063                                this.create_buffer_for_peer(&buffer, peer_id, cx).into()
 9064                            })?;
 9065                            locations.push(proto::Location {
 9066                                buffer_id,
 9067                                start: Some(start),
 9068                                end: Some(end),
 9069                            });
 9070                        }
 9071                    }
 9072                    SearchResult::LimitReached => limit_reached = true,
 9073                }
 9074            }
 9075            Ok(proto::SearchProjectResponse {
 9076                locations,
 9077                limit_reached,
 9078            })
 9079        })
 9080        .await
 9081    }
 9082
 9083    async fn handle_open_buffer_for_symbol(
 9084        this: Model<Self>,
 9085        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
 9086        _: Arc<Client>,
 9087        mut cx: AsyncAppContext,
 9088    ) -> Result<proto::OpenBufferForSymbolResponse> {
 9089        let peer_id = envelope.original_sender_id()?;
 9090        let symbol = envelope
 9091            .payload
 9092            .symbol
 9093            .ok_or_else(|| anyhow!("invalid symbol"))?;
 9094        let symbol = Self::deserialize_symbol(symbol)?;
 9095        let symbol = this.update(&mut cx, |this, _| {
 9096            let signature = this.symbol_signature(&symbol.path);
 9097            if signature == symbol.signature {
 9098                Ok(symbol)
 9099            } else {
 9100                Err(anyhow!("invalid symbol signature"))
 9101            }
 9102        })??;
 9103        let buffer = this
 9104            .update(&mut cx, |this, cx| {
 9105                this.open_buffer_for_symbol(
 9106                    &Symbol {
 9107                        language_server_name: symbol.language_server_name,
 9108                        source_worktree_id: symbol.source_worktree_id,
 9109                        path: symbol.path,
 9110                        name: symbol.name,
 9111                        kind: symbol.kind,
 9112                        range: symbol.range,
 9113                        signature: symbol.signature,
 9114                        label: CodeLabel {
 9115                            text: Default::default(),
 9116                            runs: Default::default(),
 9117                            filter_range: Default::default(),
 9118                        },
 9119                    },
 9120                    cx,
 9121                )
 9122            })?
 9123            .await?;
 9124
 9125        this.update(&mut cx, |this, cx| {
 9126            let is_private = buffer
 9127                .read(cx)
 9128                .file()
 9129                .map(|f| f.is_private())
 9130                .unwrap_or_default();
 9131            if is_private {
 9132                Err(anyhow!(ErrorCode::UnsharedItem))
 9133            } else {
 9134                Ok(proto::OpenBufferForSymbolResponse {
 9135                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9136                })
 9137            }
 9138        })?
 9139    }
 9140
 9141    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
 9142        let mut hasher = Sha256::new();
 9143        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
 9144        hasher.update(project_path.path.to_string_lossy().as_bytes());
 9145        hasher.update(self.nonce.to_be_bytes());
 9146        hasher.finalize().as_slice().try_into().unwrap()
 9147    }
 9148
 9149    async fn handle_open_buffer_by_id(
 9150        this: Model<Self>,
 9151        envelope: TypedEnvelope<proto::OpenBufferById>,
 9152        _: Arc<Client>,
 9153        mut cx: AsyncAppContext,
 9154    ) -> Result<proto::OpenBufferResponse> {
 9155        let peer_id = envelope.original_sender_id()?;
 9156        let buffer_id = BufferId::new(envelope.payload.id)?;
 9157        let buffer = this
 9158            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
 9159            .await?;
 9160        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9161    }
 9162
 9163    async fn handle_open_buffer_by_path(
 9164        this: Model<Self>,
 9165        envelope: TypedEnvelope<proto::OpenBufferByPath>,
 9166        _: Arc<Client>,
 9167        mut cx: AsyncAppContext,
 9168    ) -> Result<proto::OpenBufferResponse> {
 9169        let peer_id = envelope.original_sender_id()?;
 9170        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 9171        let open_buffer = this.update(&mut cx, |this, cx| {
 9172            this.open_buffer(
 9173                ProjectPath {
 9174                    worktree_id,
 9175                    path: PathBuf::from(envelope.payload.path).into(),
 9176                },
 9177                cx,
 9178            )
 9179        })?;
 9180
 9181        let buffer = open_buffer.await?;
 9182        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9183    }
 9184
 9185    fn respond_to_open_buffer_request(
 9186        this: Model<Self>,
 9187        buffer: Model<Buffer>,
 9188        peer_id: proto::PeerId,
 9189        cx: &mut AsyncAppContext,
 9190    ) -> Result<proto::OpenBufferResponse> {
 9191        this.update(cx, |this, cx| {
 9192            let is_private = buffer
 9193                .read(cx)
 9194                .file()
 9195                .map(|f| f.is_private())
 9196                .unwrap_or_default();
 9197            if is_private {
 9198                Err(anyhow!(ErrorCode::UnsharedItem))
 9199            } else {
 9200                Ok(proto::OpenBufferResponse {
 9201                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9202                })
 9203            }
 9204        })?
 9205    }
 9206
 9207    fn serialize_project_transaction_for_peer(
 9208        &mut self,
 9209        project_transaction: ProjectTransaction,
 9210        peer_id: proto::PeerId,
 9211        cx: &mut AppContext,
 9212    ) -> proto::ProjectTransaction {
 9213        let mut serialized_transaction = proto::ProjectTransaction {
 9214            buffer_ids: Default::default(),
 9215            transactions: Default::default(),
 9216        };
 9217        for (buffer, transaction) in project_transaction.0 {
 9218            serialized_transaction
 9219                .buffer_ids
 9220                .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
 9221            serialized_transaction
 9222                .transactions
 9223                .push(language::proto::serialize_transaction(&transaction));
 9224        }
 9225        serialized_transaction
 9226    }
 9227
 9228    fn deserialize_project_transaction(
 9229        &mut self,
 9230        message: proto::ProjectTransaction,
 9231        push_to_history: bool,
 9232        cx: &mut ModelContext<Self>,
 9233    ) -> Task<Result<ProjectTransaction>> {
 9234        cx.spawn(move |this, mut cx| async move {
 9235            let mut project_transaction = ProjectTransaction::default();
 9236            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
 9237            {
 9238                let buffer_id = BufferId::new(buffer_id)?;
 9239                let buffer = this
 9240                    .update(&mut cx, |this, cx| {
 9241                        this.wait_for_remote_buffer(buffer_id, cx)
 9242                    })?
 9243                    .await?;
 9244                let transaction = language::proto::deserialize_transaction(transaction)?;
 9245                project_transaction.0.insert(buffer, transaction);
 9246            }
 9247
 9248            for (buffer, transaction) in &project_transaction.0 {
 9249                buffer
 9250                    .update(&mut cx, |buffer, _| {
 9251                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 9252                    })?
 9253                    .await?;
 9254
 9255                if push_to_history {
 9256                    buffer.update(&mut cx, |buffer, _| {
 9257                        buffer.push_transaction(transaction.clone(), Instant::now());
 9258                    })?;
 9259                }
 9260            }
 9261
 9262            Ok(project_transaction)
 9263        })
 9264    }
 9265
 9266    fn create_buffer_for_peer(
 9267        &mut self,
 9268        buffer: &Model<Buffer>,
 9269        peer_id: proto::PeerId,
 9270        cx: &mut AppContext,
 9271    ) -> BufferId {
 9272        let buffer_id = buffer.read(cx).remote_id();
 9273        if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
 9274            updates_tx
 9275                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
 9276                .ok();
 9277        }
 9278        buffer_id
 9279    }
 9280
 9281    fn wait_for_remote_buffer(
 9282        &mut self,
 9283        id: BufferId,
 9284        cx: &mut ModelContext<Self>,
 9285    ) -> Task<Result<Model<Buffer>>> {
 9286        let buffer = self
 9287            .opened_buffers
 9288            .get(&id)
 9289            .and_then(|buffer| buffer.upgrade());
 9290
 9291        if let Some(buffer) = buffer {
 9292            return Task::ready(Ok(buffer));
 9293        }
 9294
 9295        let (tx, rx) = oneshot::channel();
 9296        self.loading_buffers.entry(id).or_default().push(tx);
 9297
 9298        cx.background_executor().spawn(async move { rx.await? })
 9299    }
 9300
 9301    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 9302        let project_id = match self.client_state {
 9303            ProjectClientState::Remote {
 9304                sharing_has_stopped,
 9305                remote_id,
 9306                ..
 9307            } => {
 9308                if sharing_has_stopped {
 9309                    return Task::ready(Err(anyhow!(
 9310                        "can't synchronize remote buffers on a readonly project"
 9311                    )));
 9312                } else {
 9313                    remote_id
 9314                }
 9315            }
 9316            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
 9317                return Task::ready(Err(anyhow!(
 9318                    "can't synchronize remote buffers on a local project"
 9319                )))
 9320            }
 9321        };
 9322
 9323        let client = self.client.clone();
 9324        cx.spawn(move |this, mut cx| async move {
 9325            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
 9326                let buffers = this
 9327                    .opened_buffers
 9328                    .iter()
 9329                    .filter_map(|(id, buffer)| {
 9330                        let buffer = buffer.upgrade()?;
 9331                        Some(proto::BufferVersion {
 9332                            id: (*id).into(),
 9333                            version: language::proto::serialize_version(&buffer.read(cx).version),
 9334                        })
 9335                    })
 9336                    .collect();
 9337                let incomplete_buffer_ids = this
 9338                    .incomplete_remote_buffers
 9339                    .keys()
 9340                    .copied()
 9341                    .collect::<Vec<_>>();
 9342
 9343                (buffers, incomplete_buffer_ids)
 9344            })?;
 9345            let response = client
 9346                .request(proto::SynchronizeBuffers {
 9347                    project_id,
 9348                    buffers,
 9349                })
 9350                .await?;
 9351
 9352            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
 9353                response
 9354                    .buffers
 9355                    .into_iter()
 9356                    .map(|buffer| {
 9357                        let client = client.clone();
 9358                        let buffer_id = match BufferId::new(buffer.id) {
 9359                            Ok(id) => id,
 9360                            Err(e) => {
 9361                                return Task::ready(Err(e));
 9362                            }
 9363                        };
 9364                        let remote_version = language::proto::deserialize_version(&buffer.version);
 9365                        if let Some(buffer) = this.buffer_for_id(buffer_id) {
 9366                            let operations =
 9367                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
 9368                            cx.background_executor().spawn(async move {
 9369                                let operations = operations.await;
 9370                                for chunk in split_operations(operations) {
 9371                                    client
 9372                                        .request(proto::UpdateBuffer {
 9373                                            project_id,
 9374                                            buffer_id: buffer_id.into(),
 9375                                            operations: chunk,
 9376                                        })
 9377                                        .await?;
 9378                                }
 9379                                anyhow::Ok(())
 9380                            })
 9381                        } else {
 9382                            Task::ready(Ok(()))
 9383                        }
 9384                    })
 9385                    .collect::<Vec<_>>()
 9386            })?;
 9387
 9388            // Any incomplete buffers have open requests waiting. Request that the host sends
 9389            // creates these buffers for us again to unblock any waiting futures.
 9390            for id in incomplete_buffer_ids {
 9391                cx.background_executor()
 9392                    .spawn(client.request(proto::OpenBufferById {
 9393                        project_id,
 9394                        id: id.into(),
 9395                    }))
 9396                    .detach();
 9397            }
 9398
 9399            futures::future::join_all(send_updates_for_buffers)
 9400                .await
 9401                .into_iter()
 9402                .collect()
 9403        })
 9404    }
 9405
 9406    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
 9407        self.worktrees()
 9408            .map(|worktree| {
 9409                let worktree = worktree.read(cx);
 9410                proto::WorktreeMetadata {
 9411                    id: worktree.id().to_proto(),
 9412                    root_name: worktree.root_name().into(),
 9413                    visible: worktree.is_visible(),
 9414                    abs_path: worktree.abs_path().to_string_lossy().into(),
 9415                }
 9416            })
 9417            .collect()
 9418    }
 9419
 9420    fn set_worktrees_from_proto(
 9421        &mut self,
 9422        worktrees: Vec<proto::WorktreeMetadata>,
 9423        cx: &mut ModelContext<Project>,
 9424    ) -> Result<()> {
 9425        let replica_id = self.replica_id();
 9426        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
 9427
 9428        let mut old_worktrees_by_id = self
 9429            .worktrees
 9430            .drain(..)
 9431            .filter_map(|worktree| {
 9432                let worktree = worktree.upgrade()?;
 9433                Some((worktree.read(cx).id(), worktree))
 9434            })
 9435            .collect::<HashMap<_, _>>();
 9436
 9437        for worktree in worktrees {
 9438            if let Some(old_worktree) =
 9439                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
 9440            {
 9441                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
 9442            } else {
 9443                let worktree =
 9444                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
 9445                let _ = self.add_worktree(&worktree, cx);
 9446            }
 9447        }
 9448
 9449        self.metadata_changed(cx);
 9450        for id in old_worktrees_by_id.keys() {
 9451            cx.emit(Event::WorktreeRemoved(*id));
 9452        }
 9453
 9454        Ok(())
 9455    }
 9456
 9457    fn set_collaborators_from_proto(
 9458        &mut self,
 9459        messages: Vec<proto::Collaborator>,
 9460        cx: &mut ModelContext<Self>,
 9461    ) -> Result<()> {
 9462        let mut collaborators = HashMap::default();
 9463        for message in messages {
 9464            let collaborator = Collaborator::from_proto(message)?;
 9465            collaborators.insert(collaborator.peer_id, collaborator);
 9466        }
 9467        for old_peer_id in self.collaborators.keys() {
 9468            if !collaborators.contains_key(old_peer_id) {
 9469                cx.emit(Event::CollaboratorLeft(*old_peer_id));
 9470            }
 9471        }
 9472        self.collaborators = collaborators;
 9473        Ok(())
 9474    }
 9475
 9476    fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
 9477        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
 9478        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
 9479        let kind = unsafe { mem::transmute(serialized_symbol.kind) };
 9480        let path = ProjectPath {
 9481            worktree_id,
 9482            path: PathBuf::from(serialized_symbol.path).into(),
 9483        };
 9484
 9485        let start = serialized_symbol
 9486            .start
 9487            .ok_or_else(|| anyhow!("invalid start"))?;
 9488        let end = serialized_symbol
 9489            .end
 9490            .ok_or_else(|| anyhow!("invalid end"))?;
 9491        Ok(CoreSymbol {
 9492            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
 9493            source_worktree_id,
 9494            path,
 9495            name: serialized_symbol.name,
 9496            range: Unclipped(PointUtf16::new(start.row, start.column))
 9497                ..Unclipped(PointUtf16::new(end.row, end.column)),
 9498            kind,
 9499            signature: serialized_symbol
 9500                .signature
 9501                .try_into()
 9502                .map_err(|_| anyhow!("invalid signature"))?,
 9503        })
 9504    }
 9505
 9506    fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
 9507        proto::Completion {
 9508            old_start: Some(serialize_anchor(&completion.old_range.start)),
 9509            old_end: Some(serialize_anchor(&completion.old_range.end)),
 9510            new_text: completion.new_text.clone(),
 9511            server_id: completion.server_id.0 as u64,
 9512            lsp_completion: serde_json::to_vec(&completion.lsp_completion).unwrap(),
 9513        }
 9514    }
 9515
 9516    fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
 9517        let old_start = completion
 9518            .old_start
 9519            .and_then(deserialize_anchor)
 9520            .ok_or_else(|| anyhow!("invalid old start"))?;
 9521        let old_end = completion
 9522            .old_end
 9523            .and_then(deserialize_anchor)
 9524            .ok_or_else(|| anyhow!("invalid old end"))?;
 9525        let lsp_completion = serde_json::from_slice(&completion.lsp_completion)?;
 9526
 9527        Ok(CoreCompletion {
 9528            old_range: old_start..old_end,
 9529            new_text: completion.new_text,
 9530            server_id: LanguageServerId(completion.server_id as usize),
 9531            lsp_completion,
 9532        })
 9533    }
 9534
 9535    fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
 9536        proto::CodeAction {
 9537            server_id: action.server_id.0 as u64,
 9538            start: Some(serialize_anchor(&action.range.start)),
 9539            end: Some(serialize_anchor(&action.range.end)),
 9540            lsp_action: serde_json::to_vec(&action.lsp_action).unwrap(),
 9541        }
 9542    }
 9543
 9544    fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
 9545        let start = action
 9546            .start
 9547            .and_then(deserialize_anchor)
 9548            .ok_or_else(|| anyhow!("invalid start"))?;
 9549        let end = action
 9550            .end
 9551            .and_then(deserialize_anchor)
 9552            .ok_or_else(|| anyhow!("invalid end"))?;
 9553        let lsp_action = serde_json::from_slice(&action.lsp_action)?;
 9554        Ok(CodeAction {
 9555            server_id: LanguageServerId(action.server_id as usize),
 9556            range: start..end,
 9557            lsp_action,
 9558        })
 9559    }
 9560
 9561    async fn handle_buffer_saved(
 9562        this: Model<Self>,
 9563        envelope: TypedEnvelope<proto::BufferSaved>,
 9564        _: Arc<Client>,
 9565        mut cx: AsyncAppContext,
 9566    ) -> Result<()> {
 9567        let fingerprint = Default::default();
 9568        let version = deserialize_version(&envelope.payload.version);
 9569        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9570        let mtime = envelope.payload.mtime.map(|time| time.into());
 9571
 9572        this.update(&mut cx, |this, cx| {
 9573            let buffer = this
 9574                .opened_buffers
 9575                .get(&buffer_id)
 9576                .and_then(|buffer| buffer.upgrade())
 9577                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
 9578            if let Some(buffer) = buffer {
 9579                buffer.update(cx, |buffer, cx| {
 9580                    buffer.did_save(version, fingerprint, mtime, cx);
 9581                });
 9582            }
 9583            Ok(())
 9584        })?
 9585    }
 9586
 9587    async fn handle_buffer_reloaded(
 9588        this: Model<Self>,
 9589        envelope: TypedEnvelope<proto::BufferReloaded>,
 9590        _: Arc<Client>,
 9591        mut cx: AsyncAppContext,
 9592    ) -> Result<()> {
 9593        let payload = envelope.payload;
 9594        let version = deserialize_version(&payload.version);
 9595        let fingerprint = RopeFingerprint::default();
 9596        let line_ending = deserialize_line_ending(
 9597            proto::LineEnding::from_i32(payload.line_ending)
 9598                .ok_or_else(|| anyhow!("missing line ending"))?,
 9599        );
 9600        let mtime = payload.mtime.map(|time| time.into());
 9601        let buffer_id = BufferId::new(payload.buffer_id)?;
 9602        this.update(&mut cx, |this, cx| {
 9603            let buffer = this
 9604                .opened_buffers
 9605                .get(&buffer_id)
 9606                .and_then(|buffer| buffer.upgrade())
 9607                .or_else(|| this.incomplete_remote_buffers.get(&buffer_id).cloned());
 9608            if let Some(buffer) = buffer {
 9609                buffer.update(cx, |buffer, cx| {
 9610                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
 9611                });
 9612            }
 9613            Ok(())
 9614        })?
 9615    }
 9616
 9617    #[allow(clippy::type_complexity)]
 9618    fn edits_from_lsp(
 9619        &mut self,
 9620        buffer: &Model<Buffer>,
 9621        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
 9622        server_id: LanguageServerId,
 9623        version: Option<i32>,
 9624        cx: &mut ModelContext<Self>,
 9625    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
 9626        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
 9627        cx.background_executor().spawn(async move {
 9628            let snapshot = snapshot?;
 9629            let mut lsp_edits = lsp_edits
 9630                .into_iter()
 9631                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
 9632                .collect::<Vec<_>>();
 9633            lsp_edits.sort_by_key(|(range, _)| range.start);
 9634
 9635            let mut lsp_edits = lsp_edits.into_iter().peekable();
 9636            let mut edits = Vec::new();
 9637            while let Some((range, mut new_text)) = lsp_edits.next() {
 9638                // Clip invalid ranges provided by the language server.
 9639                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
 9640                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
 9641
 9642                // Combine any LSP edits that are adjacent.
 9643                //
 9644                // Also, combine LSP edits that are separated from each other by only
 9645                // a newline. This is important because for some code actions,
 9646                // Rust-analyzer rewrites the entire buffer via a series of edits that
 9647                // are separated by unchanged newline characters.
 9648                //
 9649                // In order for the diffing logic below to work properly, any edits that
 9650                // cancel each other out must be combined into one.
 9651                while let Some((next_range, next_text)) = lsp_edits.peek() {
 9652                    if next_range.start.0 > range.end {
 9653                        if next_range.start.0.row > range.end.row + 1
 9654                            || next_range.start.0.column > 0
 9655                            || snapshot.clip_point_utf16(
 9656                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
 9657                                Bias::Left,
 9658                            ) > range.end
 9659                        {
 9660                            break;
 9661                        }
 9662                        new_text.push('\n');
 9663                    }
 9664                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
 9665                    new_text.push_str(next_text);
 9666                    lsp_edits.next();
 9667                }
 9668
 9669                // For multiline edits, perform a diff of the old and new text so that
 9670                // we can identify the changes more precisely, preserving the locations
 9671                // of any anchors positioned in the unchanged regions.
 9672                if range.end.row > range.start.row {
 9673                    let mut offset = range.start.to_offset(&snapshot);
 9674                    let old_text = snapshot.text_for_range(range).collect::<String>();
 9675
 9676                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
 9677                    let mut moved_since_edit = true;
 9678                    for change in diff.iter_all_changes() {
 9679                        let tag = change.tag();
 9680                        let value = change.value();
 9681                        match tag {
 9682                            ChangeTag::Equal => {
 9683                                offset += value.len();
 9684                                moved_since_edit = true;
 9685                            }
 9686                            ChangeTag::Delete => {
 9687                                let start = snapshot.anchor_after(offset);
 9688                                let end = snapshot.anchor_before(offset + value.len());
 9689                                if moved_since_edit {
 9690                                    edits.push((start..end, String::new()));
 9691                                } else {
 9692                                    edits.last_mut().unwrap().0.end = end;
 9693                                }
 9694                                offset += value.len();
 9695                                moved_since_edit = false;
 9696                            }
 9697                            ChangeTag::Insert => {
 9698                                if moved_since_edit {
 9699                                    let anchor = snapshot.anchor_after(offset);
 9700                                    edits.push((anchor..anchor, value.to_string()));
 9701                                } else {
 9702                                    edits.last_mut().unwrap().1.push_str(value);
 9703                                }
 9704                                moved_since_edit = false;
 9705                            }
 9706                        }
 9707                    }
 9708                } else if range.end == range.start {
 9709                    let anchor = snapshot.anchor_after(range.start);
 9710                    edits.push((anchor..anchor, new_text));
 9711                } else {
 9712                    let edit_start = snapshot.anchor_after(range.start);
 9713                    let edit_end = snapshot.anchor_before(range.end);
 9714                    edits.push((edit_start..edit_end, new_text));
 9715                }
 9716            }
 9717
 9718            Ok(edits)
 9719        })
 9720    }
 9721
 9722    fn buffer_snapshot_for_lsp_version(
 9723        &mut self,
 9724        buffer: &Model<Buffer>,
 9725        server_id: LanguageServerId,
 9726        version: Option<i32>,
 9727        cx: &AppContext,
 9728    ) -> Result<TextBufferSnapshot> {
 9729        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
 9730
 9731        if let Some(version) = version {
 9732            let buffer_id = buffer.read(cx).remote_id();
 9733            let snapshots = self
 9734                .buffer_snapshots
 9735                .get_mut(&buffer_id)
 9736                .and_then(|m| m.get_mut(&server_id))
 9737                .ok_or_else(|| {
 9738                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
 9739                })?;
 9740
 9741            let found_snapshot = snapshots
 9742                .binary_search_by_key(&version, |e| e.version)
 9743                .map(|ix| snapshots[ix].snapshot.clone())
 9744                .map_err(|_| {
 9745                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
 9746                })?;
 9747
 9748            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
 9749            Ok(found_snapshot)
 9750        } else {
 9751            Ok((buffer.read(cx)).text_snapshot())
 9752        }
 9753    }
 9754
 9755    pub fn language_servers(
 9756        &self,
 9757    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
 9758        self.language_server_ids
 9759            .iter()
 9760            .map(|((worktree_id, server_name), server_id)| {
 9761                (*server_id, server_name.clone(), *worktree_id)
 9762            })
 9763    }
 9764
 9765    pub fn supplementary_language_servers(
 9766        &self,
 9767    ) -> impl '_
 9768           + Iterator<
 9769        Item = (
 9770            &LanguageServerId,
 9771            &(LanguageServerName, Arc<LanguageServer>),
 9772        ),
 9773    > {
 9774        self.supplementary_language_servers.iter()
 9775    }
 9776
 9777    pub fn language_server_adapter_for_id(
 9778        &self,
 9779        id: LanguageServerId,
 9780    ) -> Option<Arc<CachedLspAdapter>> {
 9781        if let Some(LanguageServerState::Running { adapter, .. }) = self.language_servers.get(&id) {
 9782            Some(adapter.clone())
 9783        } else {
 9784            None
 9785        }
 9786    }
 9787
 9788    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
 9789        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
 9790            Some(server.clone())
 9791        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
 9792            Some(Arc::clone(server))
 9793        } else {
 9794            None
 9795        }
 9796    }
 9797
 9798    pub fn language_servers_for_buffer(
 9799        &self,
 9800        buffer: &Buffer,
 9801        cx: &AppContext,
 9802    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
 9803        self.language_server_ids_for_buffer(buffer, cx)
 9804            .into_iter()
 9805            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
 9806                LanguageServerState::Running {
 9807                    adapter, server, ..
 9808                } => Some((adapter, server)),
 9809                _ => None,
 9810            })
 9811    }
 9812
 9813    fn primary_language_server_for_buffer(
 9814        &self,
 9815        buffer: &Buffer,
 9816        cx: &AppContext,
 9817    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
 9818        self.language_servers_for_buffer(buffer, cx)
 9819            .find(|s| s.0.is_primary)
 9820    }
 9821
 9822    pub fn language_server_for_buffer(
 9823        &self,
 9824        buffer: &Buffer,
 9825        server_id: LanguageServerId,
 9826        cx: &AppContext,
 9827    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
 9828        self.language_servers_for_buffer(buffer, cx)
 9829            .find(|(_, s)| s.server_id() == server_id)
 9830    }
 9831
 9832    fn language_server_ids_for_buffer(
 9833        &self,
 9834        buffer: &Buffer,
 9835        cx: &AppContext,
 9836    ) -> Vec<LanguageServerId> {
 9837        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
 9838            let worktree_id = file.worktree_id(cx);
 9839            self.languages
 9840                .lsp_adapters(&language)
 9841                .iter()
 9842                .flat_map(|adapter| {
 9843                    let key = (worktree_id, adapter.name.clone());
 9844                    self.language_server_ids.get(&key).copied()
 9845                })
 9846                .collect()
 9847        } else {
 9848            Vec::new()
 9849        }
 9850    }
 9851}
 9852
 9853async fn populate_labels_for_symbols(
 9854    symbols: Vec<CoreSymbol>,
 9855    language_registry: &Arc<LanguageRegistry>,
 9856    default_language: Option<Arc<Language>>,
 9857    lsp_adapter: Option<Arc<CachedLspAdapter>>,
 9858    output: &mut Vec<Symbol>,
 9859) {
 9860    let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
 9861
 9862    for symbol in symbols {
 9863        let language = language_registry
 9864            .language_for_file_path(&symbol.path.path)
 9865            .await
 9866            .log_err()
 9867            .or_else(|| default_language.clone());
 9868        symbols_by_language
 9869            .entry(language)
 9870            .or_default()
 9871            .push(symbol);
 9872    }
 9873
 9874    let mut label_params = Vec::new();
 9875    for (language, mut symbols) in symbols_by_language {
 9876        label_params.clear();
 9877        label_params.extend(
 9878            symbols
 9879                .iter_mut()
 9880                .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
 9881        );
 9882
 9883        let mut labels = Vec::new();
 9884        if let Some(language) = language {
 9885            let lsp_adapter = lsp_adapter
 9886                .clone()
 9887                .or_else(|| language_registry.lsp_adapters(&language).first().cloned());
 9888            if let Some(lsp_adapter) = lsp_adapter {
 9889                labels = lsp_adapter
 9890                    .labels_for_symbols(&label_params, &language)
 9891                    .await
 9892                    .log_err()
 9893                    .unwrap_or_default();
 9894            }
 9895        }
 9896
 9897        for ((symbol, (name, _)), label) in symbols
 9898            .into_iter()
 9899            .zip(label_params.drain(..))
 9900            .zip(labels.into_iter().chain(iter::repeat(None)))
 9901        {
 9902            output.push(Symbol {
 9903                language_server_name: symbol.language_server_name,
 9904                source_worktree_id: symbol.source_worktree_id,
 9905                path: symbol.path,
 9906                label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
 9907                name,
 9908                kind: symbol.kind,
 9909                range: symbol.range,
 9910                signature: symbol.signature,
 9911            });
 9912        }
 9913    }
 9914}
 9915
 9916async fn populate_labels_for_completions(
 9917    mut new_completions: Vec<CoreCompletion>,
 9918    language_registry: &Arc<LanguageRegistry>,
 9919    language: Option<Arc<Language>>,
 9920    lsp_adapter: Option<Arc<CachedLspAdapter>>,
 9921    completions: &mut Vec<Completion>,
 9922) {
 9923    let lsp_completions = new_completions
 9924        .iter_mut()
 9925        .map(|completion| mem::take(&mut completion.lsp_completion))
 9926        .collect::<Vec<_>>();
 9927
 9928    let labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
 9929        lsp_adapter
 9930            .labels_for_completions(&lsp_completions, language)
 9931            .await
 9932            .log_err()
 9933            .unwrap_or_default()
 9934    } else {
 9935        Vec::new()
 9936    };
 9937
 9938    for ((completion, lsp_completion), label) in new_completions
 9939        .into_iter()
 9940        .zip(lsp_completions)
 9941        .zip(labels.into_iter().chain(iter::repeat(None)))
 9942    {
 9943        let documentation = if let Some(docs) = &lsp_completion.documentation {
 9944            Some(prepare_completion_documentation(docs, &language_registry, language.clone()).await)
 9945        } else {
 9946            None
 9947        };
 9948
 9949        completions.push(Completion {
 9950            old_range: completion.old_range,
 9951            new_text: completion.new_text,
 9952            label: label.unwrap_or_else(|| {
 9953                CodeLabel::plain(
 9954                    lsp_completion.label.clone(),
 9955                    lsp_completion.filter_text.as_deref(),
 9956                )
 9957            }),
 9958            server_id: completion.server_id,
 9959            documentation,
 9960            lsp_completion,
 9961        })
 9962    }
 9963}
 9964
 9965fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
 9966    code_actions
 9967        .iter()
 9968        .flat_map(|(kind, enabled)| {
 9969            if *enabled {
 9970                Some(kind.clone().into())
 9971            } else {
 9972                None
 9973            }
 9974        })
 9975        .collect()
 9976}
 9977
 9978#[allow(clippy::too_many_arguments)]
 9979async fn search_snapshots(
 9980    snapshots: &Vec<LocalSnapshot>,
 9981    worker_start_ix: usize,
 9982    worker_end_ix: usize,
 9983    query: &SearchQuery,
 9984    results_tx: &Sender<SearchMatchCandidate>,
 9985    opened_buffers: &HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
 9986    include_root: bool,
 9987    fs: &Arc<dyn Fs>,
 9988) {
 9989    let mut snapshot_start_ix = 0;
 9990    let mut abs_path = PathBuf::new();
 9991
 9992    for snapshot in snapshots {
 9993        let snapshot_end_ix = snapshot_start_ix
 9994            + if query.include_ignored() {
 9995                snapshot.file_count()
 9996            } else {
 9997                snapshot.visible_file_count()
 9998            };
 9999        if worker_end_ix <= snapshot_start_ix {
10000            break;
10001        } else if worker_start_ix > snapshot_end_ix {
10002            snapshot_start_ix = snapshot_end_ix;
10003            continue;
10004        } else {
10005            let start_in_snapshot = worker_start_ix.saturating_sub(snapshot_start_ix);
10006            let end_in_snapshot = cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
10007
10008            for entry in snapshot
10009                .files(false, start_in_snapshot)
10010                .take(end_in_snapshot - start_in_snapshot)
10011            {
10012                if results_tx.is_closed() {
10013                    break;
10014                }
10015                if opened_buffers.contains_key(&entry.path) {
10016                    continue;
10017                }
10018
10019                let matched_path = if include_root {
10020                    let mut full_path = PathBuf::from(snapshot.root_name());
10021                    full_path.push(&entry.path);
10022                    query.file_matches(Some(&full_path))
10023                } else {
10024                    query.file_matches(Some(&entry.path))
10025                };
10026
10027                let matches = if matched_path {
10028                    abs_path.clear();
10029                    abs_path.push(&snapshot.abs_path());
10030                    abs_path.push(&entry.path);
10031                    if let Some(file) = fs.open_sync(&abs_path).await.log_err() {
10032                        query.detect(file).unwrap_or(false)
10033                    } else {
10034                        false
10035                    }
10036                } else {
10037                    false
10038                };
10039
10040                if matches {
10041                    let project_path = SearchMatchCandidate::Path {
10042                        worktree_id: snapshot.id(),
10043                        path: entry.path.clone(),
10044                        is_ignored: entry.is_ignored,
10045                    };
10046                    if results_tx.send(project_path).await.is_err() {
10047                        return;
10048                    }
10049                }
10050            }
10051
10052            snapshot_start_ix = snapshot_end_ix;
10053        }
10054    }
10055}
10056
10057async fn search_ignored_entry(
10058    snapshot: &LocalSnapshot,
10059    ignored_entry: &Entry,
10060    fs: &Arc<dyn Fs>,
10061    query: &SearchQuery,
10062    counter_tx: &Sender<SearchMatchCandidate>,
10063) {
10064    let mut ignored_paths_to_process =
10065        VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
10066
10067    while let Some(ignored_abs_path) = ignored_paths_to_process.pop_front() {
10068        let metadata = fs
10069            .metadata(&ignored_abs_path)
10070            .await
10071            .with_context(|| format!("fetching fs metadata for {ignored_abs_path:?}"))
10072            .log_err()
10073            .flatten();
10074
10075        if let Some(fs_metadata) = metadata {
10076            if fs_metadata.is_dir {
10077                let files = fs
10078                    .read_dir(&ignored_abs_path)
10079                    .await
10080                    .with_context(|| format!("listing ignored path {ignored_abs_path:?}"))
10081                    .log_err();
10082
10083                if let Some(mut subfiles) = files {
10084                    while let Some(subfile) = subfiles.next().await {
10085                        if let Some(subfile) = subfile.log_err() {
10086                            ignored_paths_to_process.push_back(subfile);
10087                        }
10088                    }
10089                }
10090            } else if !fs_metadata.is_symlink {
10091                if !query.file_matches(Some(&ignored_abs_path))
10092                    || snapshot.is_path_excluded(ignored_entry.path.to_path_buf())
10093                {
10094                    continue;
10095                }
10096                let matches = if let Some(file) = fs
10097                    .open_sync(&ignored_abs_path)
10098                    .await
10099                    .with_context(|| format!("Opening ignored path {ignored_abs_path:?}"))
10100                    .log_err()
10101                {
10102                    query.detect(file).unwrap_or(false)
10103                } else {
10104                    false
10105                };
10106
10107                if matches {
10108                    let project_path = SearchMatchCandidate::Path {
10109                        worktree_id: snapshot.id(),
10110                        path: Arc::from(
10111                            ignored_abs_path
10112                                .strip_prefix(snapshot.abs_path())
10113                                .expect("scanning worktree-related files"),
10114                        ),
10115                        is_ignored: true,
10116                    };
10117                    if counter_tx.send(project_path).await.is_err() {
10118                        return;
10119                    }
10120                }
10121            }
10122        }
10123    }
10124}
10125
10126fn subscribe_for_copilot_events(
10127    copilot: &Model<Copilot>,
10128    cx: &mut ModelContext<'_, Project>,
10129) -> gpui::Subscription {
10130    cx.subscribe(
10131        copilot,
10132        |project, copilot, copilot_event, cx| match copilot_event {
10133            copilot::Event::CopilotLanguageServerStarted => {
10134                match copilot.read(cx).language_server() {
10135                    Some((name, copilot_server)) => {
10136                        // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
10137                        if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
10138                            let new_server_id = copilot_server.server_id();
10139                            let weak_project = cx.weak_model();
10140                            let copilot_log_subscription = copilot_server
10141                                .on_notification::<copilot::request::LogMessage, _>(
10142                                    move |params, mut cx| {
10143                                        weak_project.update(&mut cx, |_, cx| {
10144                                            cx.emit(Event::LanguageServerLog(
10145                                                new_server_id,
10146                                                params.message,
10147                                            ));
10148                                        }).ok();
10149                                    },
10150                                );
10151                            project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
10152                            project.copilot_log_subscription = Some(copilot_log_subscription);
10153                            cx.emit(Event::LanguageServerAdded(new_server_id));
10154                        }
10155                    }
10156                    None => debug_panic!("Received Copilot language server started event, but no language server is running"),
10157                }
10158            }
10159        },
10160    )
10161}
10162
10163fn glob_literal_prefix(glob: &str) -> &str {
10164    let mut literal_end = 0;
10165    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
10166        if part.contains(&['*', '?', '{', '}']) {
10167            break;
10168        } else {
10169            if i > 0 {
10170                // Account for separator prior to this part
10171                literal_end += path::MAIN_SEPARATOR.len_utf8();
10172            }
10173            literal_end += part.len();
10174        }
10175    }
10176    &glob[..literal_end]
10177}
10178
10179impl WorktreeHandle {
10180    pub fn upgrade(&self) -> Option<Model<Worktree>> {
10181        match self {
10182            WorktreeHandle::Strong(handle) => Some(handle.clone()),
10183            WorktreeHandle::Weak(handle) => handle.upgrade(),
10184        }
10185    }
10186
10187    pub fn handle_id(&self) -> usize {
10188        match self {
10189            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
10190            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
10191        }
10192    }
10193}
10194
10195impl OpenBuffer {
10196    pub fn upgrade(&self) -> Option<Model<Buffer>> {
10197        match self {
10198            OpenBuffer::Strong(handle) => Some(handle.clone()),
10199            OpenBuffer::Weak(handle) => handle.upgrade(),
10200            OpenBuffer::Operations(_) => None,
10201        }
10202    }
10203}
10204
10205pub struct PathMatchCandidateSet {
10206    pub snapshot: Snapshot,
10207    pub include_ignored: bool,
10208    pub include_root_name: bool,
10209}
10210
10211impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
10212    type Candidates = PathMatchCandidateSetIter<'a>;
10213
10214    fn id(&self) -> usize {
10215        self.snapshot.id().to_usize()
10216    }
10217
10218    fn len(&self) -> usize {
10219        if self.include_ignored {
10220            self.snapshot.file_count()
10221        } else {
10222            self.snapshot.visible_file_count()
10223        }
10224    }
10225
10226    fn prefix(&self) -> Arc<str> {
10227        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
10228            self.snapshot.root_name().into()
10229        } else if self.include_root_name {
10230            format!("{}/", self.snapshot.root_name()).into()
10231        } else {
10232            "".into()
10233        }
10234    }
10235
10236    fn candidates(&'a self, start: usize) -> Self::Candidates {
10237        PathMatchCandidateSetIter {
10238            traversal: self.snapshot.files(self.include_ignored, start),
10239        }
10240    }
10241}
10242
10243pub struct PathMatchCandidateSetIter<'a> {
10244    traversal: Traversal<'a>,
10245}
10246
10247impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
10248    type Item = fuzzy::PathMatchCandidate<'a>;
10249
10250    fn next(&mut self) -> Option<Self::Item> {
10251        self.traversal.next().map(|entry| {
10252            if let EntryKind::File(char_bag) = entry.kind {
10253                fuzzy::PathMatchCandidate {
10254                    path: &entry.path,
10255                    char_bag,
10256                }
10257            } else {
10258                unreachable!()
10259            }
10260        })
10261    }
10262}
10263
10264impl EventEmitter<Event> for Project {}
10265
10266impl<'a> Into<SettingsLocation<'a>> for &'a ProjectPath {
10267    fn into(self) -> SettingsLocation<'a> {
10268        SettingsLocation {
10269            worktree_id: self.worktree_id.to_usize(),
10270            path: self.path.as_ref(),
10271        }
10272    }
10273}
10274
10275impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
10276    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
10277        Self {
10278            worktree_id,
10279            path: path.as_ref().into(),
10280        }
10281    }
10282}
10283
10284struct ProjectLspAdapterDelegate {
10285    project: WeakModel<Project>,
10286    worktree: worktree::Snapshot,
10287    fs: Arc<dyn Fs>,
10288    http_client: Arc<dyn HttpClient>,
10289    language_registry: Arc<LanguageRegistry>,
10290    shell_env: Mutex<Option<HashMap<String, String>>>,
10291}
10292
10293impl ProjectLspAdapterDelegate {
10294    fn new(project: &Project, worktree: &Model<Worktree>, cx: &ModelContext<Project>) -> Arc<Self> {
10295        Arc::new(Self {
10296            project: cx.weak_model(),
10297            worktree: worktree.read(cx).snapshot(),
10298            fs: project.fs.clone(),
10299            http_client: project.client.http_client(),
10300            language_registry: project.languages.clone(),
10301            shell_env: Default::default(),
10302        })
10303    }
10304
10305    async fn load_shell_env(&self) {
10306        let worktree_abs_path = self.worktree.abs_path();
10307        let shell_env = load_shell_environment(&worktree_abs_path)
10308            .await
10309            .with_context(|| {
10310                format!("failed to determine load login shell environment in {worktree_abs_path:?}")
10311            })
10312            .log_err()
10313            .unwrap_or_default();
10314        *self.shell_env.lock() = Some(shell_env);
10315    }
10316}
10317
10318#[async_trait]
10319impl LspAdapterDelegate for ProjectLspAdapterDelegate {
10320    fn show_notification(&self, message: &str, cx: &mut AppContext) {
10321        self.project
10322            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())))
10323            .ok();
10324    }
10325
10326    fn http_client(&self) -> Arc<dyn HttpClient> {
10327        self.http_client.clone()
10328    }
10329
10330    fn worktree_id(&self) -> u64 {
10331        self.worktree.id().to_proto()
10332    }
10333
10334    fn worktree_root_path(&self) -> &Path {
10335        self.worktree.abs_path().as_ref()
10336    }
10337
10338    async fn shell_env(&self) -> HashMap<String, String> {
10339        self.load_shell_env().await;
10340        self.shell_env.lock().as_ref().cloned().unwrap_or_default()
10341    }
10342
10343    #[cfg(not(target_os = "windows"))]
10344    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10345        let worktree_abs_path = self.worktree.abs_path();
10346        self.load_shell_env().await;
10347        let shell_path = self
10348            .shell_env
10349            .lock()
10350            .as_ref()
10351            .and_then(|shell_env| shell_env.get("PATH").cloned());
10352        which::which_in(command, shell_path.as_ref(), &worktree_abs_path).ok()
10353    }
10354
10355    #[cfg(target_os = "windows")]
10356    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10357        // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
10358        //               there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
10359        //               SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
10360        which::which(command).ok()
10361    }
10362
10363    fn update_status(
10364        &self,
10365        server_name: LanguageServerName,
10366        status: language::LanguageServerBinaryStatus,
10367    ) {
10368        self.language_registry
10369            .update_lsp_status(server_name, status);
10370    }
10371
10372    async fn read_text_file(&self, path: PathBuf) -> Result<String> {
10373        if self.worktree.entry_for_path(&path).is_none() {
10374            return Err(anyhow!("no such path {path:?}"));
10375        }
10376        let path = self.worktree.absolutize(path.as_ref())?;
10377        let content = self.fs.load(&path).await?;
10378        Ok(content)
10379    }
10380}
10381
10382fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
10383    proto::Symbol {
10384        language_server_name: symbol.language_server_name.0.to_string(),
10385        source_worktree_id: symbol.source_worktree_id.to_proto(),
10386        worktree_id: symbol.path.worktree_id.to_proto(),
10387        path: symbol.path.path.to_string_lossy().to_string(),
10388        name: symbol.name.clone(),
10389        kind: unsafe { mem::transmute(symbol.kind) },
10390        start: Some(proto::PointUtf16 {
10391            row: symbol.range.start.0.row,
10392            column: symbol.range.start.0.column,
10393        }),
10394        end: Some(proto::PointUtf16 {
10395            row: symbol.range.end.0.row,
10396            column: symbol.range.end.0.column,
10397        }),
10398        signature: symbol.signature.to_vec(),
10399    }
10400}
10401
10402fn relativize_path(base: &Path, path: &Path) -> PathBuf {
10403    let mut path_components = path.components();
10404    let mut base_components = base.components();
10405    let mut components: Vec<Component> = Vec::new();
10406    loop {
10407        match (path_components.next(), base_components.next()) {
10408            (None, None) => break,
10409            (Some(a), None) => {
10410                components.push(a);
10411                components.extend(path_components.by_ref());
10412                break;
10413            }
10414            (None, _) => components.push(Component::ParentDir),
10415            (Some(a), Some(b)) if components.is_empty() && a == b => (),
10416            (Some(a), Some(Component::CurDir)) => components.push(a),
10417            (Some(a), Some(_)) => {
10418                components.push(Component::ParentDir);
10419                for _ in base_components {
10420                    components.push(Component::ParentDir);
10421                }
10422                components.push(a);
10423                components.extend(path_components.by_ref());
10424                break;
10425            }
10426        }
10427    }
10428    components.iter().map(|c| c.as_os_str()).collect()
10429}
10430
10431fn resolve_path(base: &Path, path: &Path) -> PathBuf {
10432    let mut result = base.to_path_buf();
10433    for component in path.components() {
10434        match component {
10435            Component::ParentDir => {
10436                result.pop();
10437            }
10438            Component::CurDir => (),
10439            _ => result.push(component),
10440        }
10441    }
10442    result
10443}
10444
10445impl Item for Buffer {
10446    fn try_open(
10447        project: &Model<Project>,
10448        path: &ProjectPath,
10449        cx: &mut AppContext,
10450    ) -> Option<Task<Result<Model<Self>>>> {
10451        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
10452    }
10453
10454    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
10455        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
10456    }
10457
10458    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
10459        File::from_dyn(self.file()).map(|file| ProjectPath {
10460            worktree_id: file.worktree_id(cx),
10461            path: file.path().clone(),
10462        })
10463    }
10464}
10465
10466impl Completion {
10467    /// A key that can be used to sort completions when displaying
10468    /// them to the user.
10469    pub fn sort_key(&self) -> (usize, &str) {
10470        let kind_key = match self.lsp_completion.kind {
10471            Some(lsp::CompletionItemKind::KEYWORD) => 0,
10472            Some(lsp::CompletionItemKind::VARIABLE) => 1,
10473            _ => 2,
10474        };
10475        (kind_key, &self.label.text[self.label.filter_range.clone()])
10476    }
10477
10478    /// Whether this completion is a snippet.
10479    pub fn is_snippet(&self) -> bool {
10480        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
10481    }
10482}
10483
10484async fn wait_for_loading_buffer(
10485    mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
10486) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
10487    loop {
10488        if let Some(result) = receiver.borrow().as_ref() {
10489            match result {
10490                Ok(buffer) => return Ok(buffer.to_owned()),
10491                Err(e) => return Err(e.to_owned()),
10492            }
10493        }
10494        receiver.next().await;
10495    }
10496}
10497
10498fn include_text(server: &lsp::LanguageServer) -> bool {
10499    server
10500        .capabilities()
10501        .text_document_sync
10502        .as_ref()
10503        .and_then(|sync| match sync {
10504            lsp::TextDocumentSyncCapability::Kind(_) => None,
10505            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
10506        })
10507        .and_then(|save_options| match save_options {
10508            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
10509            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
10510        })
10511        .unwrap_or(false)
10512}
10513
10514async fn load_shell_environment(dir: &Path) -> Result<HashMap<String, String>> {
10515    let marker = "ZED_SHELL_START";
10516    let shell = env::var("SHELL").context(
10517        "SHELL environment variable is not assigned so we can't source login environment variables",
10518    )?;
10519
10520    // What we're doing here is to spawn a shell and then `cd` into
10521    // the project directory to get the env in there as if the user
10522    // `cd`'d into it. We do that because tools like direnv, asdf, ...
10523    // hook into `cd` and only set up the env after that.
10524    //
10525    // In certain shells we need to execute additional_command in order to
10526    // trigger the behavior of direnv, etc.
10527    //
10528    //
10529    // The `exit 0` is the result of hours of debugging, trying to find out
10530    // why running this command here, without `exit 0`, would mess
10531    // up signal process for our process so that `ctrl-c` doesn't work
10532    // anymore.
10533    //
10534    // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'`  would
10535    // do that, but it does, and `exit 0` helps.
10536    let additional_command = PathBuf::from(&shell)
10537        .file_name()
10538        .and_then(|f| f.to_str())
10539        .and_then(|shell| match shell {
10540            "fish" => Some("emit fish_prompt;"),
10541            _ => None,
10542        });
10543
10544    let command = format!(
10545        "cd '{}';{} printf '%s' {marker}; /usr/bin/env; exit 0;",
10546        dir.display(),
10547        additional_command.unwrap_or("")
10548    );
10549
10550    let output = smol::process::Command::new(&shell)
10551        .args(["-i", "-c", &command])
10552        .output()
10553        .await
10554        .context("failed to spawn login shell to source login environment variables")?;
10555
10556    anyhow::ensure!(
10557        output.status.success(),
10558        "login shell exited with error {:?}",
10559        output.status
10560    );
10561
10562    let stdout = String::from_utf8_lossy(&output.stdout);
10563    let env_output_start = stdout.find(marker).ok_or_else(|| {
10564        anyhow!(
10565            "failed to parse output of `env` command in login shell: {}",
10566            stdout
10567        )
10568    })?;
10569
10570    let mut parsed_env = HashMap::default();
10571    let env_output = &stdout[env_output_start + marker.len()..];
10572
10573    parse_env_output(env_output, |key, value| {
10574        parsed_env.insert(key, value);
10575    });
10576
10577    Ok(parsed_env)
10578}
10579
10580fn serialize_blame_buffer_response(blame: git::blame::Blame) -> proto::BlameBufferResponse {
10581    let entries = blame
10582        .entries
10583        .into_iter()
10584        .map(|entry| proto::BlameEntry {
10585            sha: entry.sha.as_bytes().into(),
10586            start_line: entry.range.start,
10587            end_line: entry.range.end,
10588            original_line_number: entry.original_line_number,
10589            author: entry.author.clone(),
10590            author_mail: entry.author_mail.clone(),
10591            author_time: entry.author_time,
10592            author_tz: entry.author_tz.clone(),
10593            committer: entry.committer.clone(),
10594            committer_mail: entry.committer_mail.clone(),
10595            committer_time: entry.committer_time,
10596            committer_tz: entry.committer_tz.clone(),
10597            summary: entry.summary.clone(),
10598            previous: entry.previous.clone(),
10599            filename: entry.filename.clone(),
10600        })
10601        .collect::<Vec<_>>();
10602
10603    let messages = blame
10604        .messages
10605        .into_iter()
10606        .map(|(oid, message)| proto::CommitMessage {
10607            oid: oid.as_bytes().into(),
10608            message,
10609        })
10610        .collect::<Vec<_>>();
10611
10612    let permalinks = blame
10613        .permalinks
10614        .into_iter()
10615        .map(|(oid, url)| proto::CommitPermalink {
10616            oid: oid.as_bytes().into(),
10617            permalink: url.to_string(),
10618        })
10619        .collect::<Vec<_>>();
10620
10621    proto::BlameBufferResponse {
10622        entries,
10623        messages,
10624        permalinks,
10625    }
10626}
10627
10628fn deserialize_blame_buffer_response(response: proto::BlameBufferResponse) -> git::blame::Blame {
10629    let entries = response
10630        .entries
10631        .into_iter()
10632        .filter_map(|entry| {
10633            Some(git::blame::BlameEntry {
10634                sha: git::Oid::from_bytes(&entry.sha).ok()?,
10635                range: entry.start_line..entry.end_line,
10636                original_line_number: entry.original_line_number,
10637                committer: entry.committer,
10638                committer_time: entry.committer_time,
10639                committer_tz: entry.committer_tz,
10640                committer_mail: entry.committer_mail,
10641                author: entry.author,
10642                author_mail: entry.author_mail,
10643                author_time: entry.author_time,
10644                author_tz: entry.author_tz,
10645                summary: entry.summary,
10646                previous: entry.previous,
10647                filename: entry.filename,
10648            })
10649        })
10650        .collect::<Vec<_>>();
10651
10652    let messages = response
10653        .messages
10654        .into_iter()
10655        .filter_map(|message| Some((git::Oid::from_bytes(&message.oid).ok()?, message.message)))
10656        .collect::<HashMap<_, _>>();
10657
10658    let permalinks = response
10659        .permalinks
10660        .into_iter()
10661        .filter_map(|permalink| {
10662            Some((
10663                git::Oid::from_bytes(&permalink.oid).ok()?,
10664                Url::from_str(&permalink.permalink).ok()?,
10665            ))
10666        })
10667        .collect::<HashMap<_, _>>();
10668
10669    Blame {
10670        entries,
10671        permalinks,
10672        messages,
10673    }
10674}
10675
10676fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
10677    hover
10678        .contents
10679        .retain(|hover_block| !hover_block.text.trim().is_empty());
10680    if hover.contents.is_empty() {
10681        None
10682    } else {
10683        Some(hover)
10684    }
10685}