project.rs

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