project.rs

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