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        #[cfg(target_os = "windows")]
 5453        {
 5454            use smol::process::windows::CommandExt;
 5455            child.creation_flags(windows::Win32::System::Threading::CREATE_NO_WINDOW.0);
 5456        }
 5457
 5458        if let Some(working_dir_path) = working_dir_path {
 5459            child.current_dir(working_dir_path);
 5460        }
 5461
 5462        let mut child = child
 5463            .args(arguments.iter().map(|arg| {
 5464                if let Some(buffer_abs_path) = buffer_abs_path {
 5465                    arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
 5466                } else {
 5467                    arg.replace("{buffer_path}", "Untitled")
 5468                }
 5469            }))
 5470            .stdin(smol::process::Stdio::piped())
 5471            .stdout(smol::process::Stdio::piped())
 5472            .stderr(smol::process::Stdio::piped())
 5473            .spawn()?;
 5474
 5475        let stdin = child
 5476            .stdin
 5477            .as_mut()
 5478            .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
 5479        let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
 5480        for chunk in text.chunks() {
 5481            stdin.write_all(chunk.as_bytes()).await?;
 5482        }
 5483        stdin.flush().await?;
 5484
 5485        let output = child.output().await?;
 5486        if !output.status.success() {
 5487            return Err(anyhow!(
 5488                "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
 5489                output.status.code(),
 5490                String::from_utf8_lossy(&output.stdout),
 5491                String::from_utf8_lossy(&output.stderr),
 5492            ));
 5493        }
 5494
 5495        let stdout = String::from_utf8(output.stdout)?;
 5496        Ok(Some(
 5497            buffer
 5498                .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
 5499                .await,
 5500        ))
 5501    }
 5502
 5503    #[inline(never)]
 5504    fn definition_impl(
 5505        &self,
 5506        buffer: &Model<Buffer>,
 5507        position: PointUtf16,
 5508        cx: &mut ModelContext<Self>,
 5509    ) -> Task<Result<Vec<LocationLink>>> {
 5510        self.request_lsp(
 5511            buffer.clone(),
 5512            LanguageServerToQuery::Primary,
 5513            GetDefinition { position },
 5514            cx,
 5515        )
 5516    }
 5517    pub fn definition<T: ToPointUtf16>(
 5518        &self,
 5519        buffer: &Model<Buffer>,
 5520        position: T,
 5521        cx: &mut ModelContext<Self>,
 5522    ) -> Task<Result<Vec<LocationLink>>> {
 5523        let position = position.to_point_utf16(buffer.read(cx));
 5524        self.definition_impl(buffer, position, cx)
 5525    }
 5526
 5527    fn declaration_impl(
 5528        &self,
 5529        buffer: &Model<Buffer>,
 5530        position: PointUtf16,
 5531        cx: &mut ModelContext<Self>,
 5532    ) -> Task<Result<Vec<LocationLink>>> {
 5533        self.request_lsp(
 5534            buffer.clone(),
 5535            LanguageServerToQuery::Primary,
 5536            GetDeclaration { position },
 5537            cx,
 5538        )
 5539    }
 5540
 5541    pub fn declaration<T: ToPointUtf16>(
 5542        &self,
 5543        buffer: &Model<Buffer>,
 5544        position: T,
 5545        cx: &mut ModelContext<Self>,
 5546    ) -> Task<Result<Vec<LocationLink>>> {
 5547        let position = position.to_point_utf16(buffer.read(cx));
 5548        self.declaration_impl(buffer, position, cx)
 5549    }
 5550
 5551    fn type_definition_impl(
 5552        &self,
 5553        buffer: &Model<Buffer>,
 5554        position: PointUtf16,
 5555        cx: &mut ModelContext<Self>,
 5556    ) -> Task<Result<Vec<LocationLink>>> {
 5557        self.request_lsp(
 5558            buffer.clone(),
 5559            LanguageServerToQuery::Primary,
 5560            GetTypeDefinition { position },
 5561            cx,
 5562        )
 5563    }
 5564
 5565    pub fn type_definition<T: ToPointUtf16>(
 5566        &self,
 5567        buffer: &Model<Buffer>,
 5568        position: T,
 5569        cx: &mut ModelContext<Self>,
 5570    ) -> Task<Result<Vec<LocationLink>>> {
 5571        let position = position.to_point_utf16(buffer.read(cx));
 5572        self.type_definition_impl(buffer, position, cx)
 5573    }
 5574
 5575    fn implementation_impl(
 5576        &self,
 5577        buffer: &Model<Buffer>,
 5578        position: PointUtf16,
 5579        cx: &mut ModelContext<Self>,
 5580    ) -> Task<Result<Vec<LocationLink>>> {
 5581        self.request_lsp(
 5582            buffer.clone(),
 5583            LanguageServerToQuery::Primary,
 5584            GetImplementation { position },
 5585            cx,
 5586        )
 5587    }
 5588
 5589    pub fn implementation<T: ToPointUtf16>(
 5590        &self,
 5591        buffer: &Model<Buffer>,
 5592        position: T,
 5593        cx: &mut ModelContext<Self>,
 5594    ) -> Task<Result<Vec<LocationLink>>> {
 5595        let position = position.to_point_utf16(buffer.read(cx));
 5596        self.implementation_impl(buffer, position, cx)
 5597    }
 5598
 5599    fn references_impl(
 5600        &self,
 5601        buffer: &Model<Buffer>,
 5602        position: PointUtf16,
 5603        cx: &mut ModelContext<Self>,
 5604    ) -> Task<Result<Vec<Location>>> {
 5605        self.request_lsp(
 5606            buffer.clone(),
 5607            LanguageServerToQuery::Primary,
 5608            GetReferences { position },
 5609            cx,
 5610        )
 5611    }
 5612    pub fn references<T: ToPointUtf16>(
 5613        &self,
 5614        buffer: &Model<Buffer>,
 5615        position: T,
 5616        cx: &mut ModelContext<Self>,
 5617    ) -> Task<Result<Vec<Location>>> {
 5618        let position = position.to_point_utf16(buffer.read(cx));
 5619        self.references_impl(buffer, position, cx)
 5620    }
 5621
 5622    fn document_highlights_impl(
 5623        &self,
 5624        buffer: &Model<Buffer>,
 5625        position: PointUtf16,
 5626        cx: &mut ModelContext<Self>,
 5627    ) -> Task<Result<Vec<DocumentHighlight>>> {
 5628        self.request_lsp(
 5629            buffer.clone(),
 5630            LanguageServerToQuery::Primary,
 5631            GetDocumentHighlights { position },
 5632            cx,
 5633        )
 5634    }
 5635
 5636    pub fn document_highlights<T: ToPointUtf16>(
 5637        &self,
 5638        buffer: &Model<Buffer>,
 5639        position: T,
 5640        cx: &mut ModelContext<Self>,
 5641    ) -> Task<Result<Vec<DocumentHighlight>>> {
 5642        let position = position.to_point_utf16(buffer.read(cx));
 5643        self.document_highlights_impl(buffer, position, cx)
 5644    }
 5645
 5646    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
 5647        let language_registry = self.languages.clone();
 5648
 5649        if self.is_local_or_ssh() {
 5650            let mut requests = Vec::new();
 5651            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
 5652                let Some(worktree_handle) = self.worktree_for_id(*worktree_id, cx) else {
 5653                    continue;
 5654                };
 5655                let worktree = worktree_handle.read(cx);
 5656                if !worktree.is_visible() {
 5657                    continue;
 5658                }
 5659                let worktree_abs_path = worktree.abs_path().clone();
 5660
 5661                let (adapter, language, server) = match self.language_servers.get(server_id) {
 5662                    Some(LanguageServerState::Running {
 5663                        adapter,
 5664                        language,
 5665                        server,
 5666                        ..
 5667                    }) => (adapter.clone(), language.clone(), server),
 5668
 5669                    _ => continue,
 5670                };
 5671
 5672                requests.push(
 5673                    server
 5674                        .request::<lsp::request::WorkspaceSymbolRequest>(
 5675                            lsp::WorkspaceSymbolParams {
 5676                                query: query.to_string(),
 5677                                ..Default::default()
 5678                            },
 5679                        )
 5680                        .log_err()
 5681                        .map(move |response| {
 5682                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
 5683                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
 5684                                    flat_responses.into_iter().map(|lsp_symbol| {
 5685                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
 5686                                    }).collect::<Vec<_>>()
 5687                                }
 5688                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
 5689                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
 5690                                        let location = match lsp_symbol.location {
 5691                                            OneOf::Left(location) => location,
 5692                                            OneOf::Right(_) => {
 5693                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
 5694                                                return None
 5695                                            }
 5696                                        };
 5697                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
 5698                                    }).collect::<Vec<_>>()
 5699                                }
 5700                            }).unwrap_or_default();
 5701
 5702                            (
 5703                                adapter,
 5704                                language,
 5705                                worktree_handle.downgrade(),
 5706                                worktree_abs_path,
 5707                                lsp_symbols,
 5708                            )
 5709                        }),
 5710                );
 5711            }
 5712
 5713            cx.spawn(move |this, mut cx| async move {
 5714                let responses = futures::future::join_all(requests).await;
 5715                let this = match this.upgrade() {
 5716                    Some(this) => this,
 5717                    None => return Ok(Vec::new()),
 5718                };
 5719
 5720                let mut symbols = Vec::new();
 5721                for (adapter, adapter_language, source_worktree, worktree_abs_path, lsp_symbols) in
 5722                    responses
 5723                {
 5724                    let core_symbols = this.update(&mut cx, |this, cx| {
 5725                        lsp_symbols
 5726                            .into_iter()
 5727                            .filter_map(|(symbol_name, symbol_kind, symbol_location)| {
 5728                                let abs_path = symbol_location.uri.to_file_path().ok()?;
 5729                                let source_worktree = source_worktree.upgrade()?;
 5730                                let source_worktree_id = source_worktree.read(cx).id();
 5731
 5732                                let path;
 5733                                let worktree;
 5734                                if let Some((tree, rel_path)) = this.find_worktree(&abs_path, cx) {
 5735                                    worktree = tree;
 5736                                    path = rel_path;
 5737                                } else {
 5738                                    worktree = source_worktree.clone();
 5739                                    path = relativize_path(&worktree_abs_path, &abs_path);
 5740                                }
 5741
 5742                                let worktree_id = worktree.read(cx).id();
 5743                                let project_path = ProjectPath {
 5744                                    worktree_id,
 5745                                    path: path.into(),
 5746                                };
 5747                                let signature = this.symbol_signature(&project_path);
 5748                                Some(CoreSymbol {
 5749                                    language_server_name: adapter.name.clone(),
 5750                                    source_worktree_id,
 5751                                    path: project_path,
 5752                                    kind: symbol_kind,
 5753                                    name: symbol_name,
 5754                                    range: range_from_lsp(symbol_location.range),
 5755                                    signature,
 5756                                })
 5757                            })
 5758                            .collect()
 5759                    })?;
 5760
 5761                    populate_labels_for_symbols(
 5762                        core_symbols,
 5763                        &language_registry,
 5764                        Some(adapter_language),
 5765                        Some(adapter),
 5766                        &mut symbols,
 5767                    )
 5768                    .await;
 5769                }
 5770
 5771                Ok(symbols)
 5772            })
 5773        } else if let Some(project_id) = self.remote_id() {
 5774            let request = self.client.request(proto::GetProjectSymbols {
 5775                project_id,
 5776                query: query.to_string(),
 5777            });
 5778            cx.foreground_executor().spawn(async move {
 5779                let response = request.await?;
 5780                let mut symbols = Vec::new();
 5781                let core_symbols = response
 5782                    .symbols
 5783                    .into_iter()
 5784                    .filter_map(|symbol| Self::deserialize_symbol(symbol).log_err())
 5785                    .collect::<Vec<_>>();
 5786                populate_labels_for_symbols(
 5787                    core_symbols,
 5788                    &language_registry,
 5789                    None,
 5790                    None,
 5791                    &mut symbols,
 5792                )
 5793                .await;
 5794                Ok(symbols)
 5795            })
 5796        } else {
 5797            Task::ready(Ok(Default::default()))
 5798        }
 5799    }
 5800
 5801    pub fn open_buffer_for_symbol(
 5802        &mut self,
 5803        symbol: &Symbol,
 5804        cx: &mut ModelContext<Self>,
 5805    ) -> Task<Result<Model<Buffer>>> {
 5806        if self.is_local_or_ssh() {
 5807            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
 5808                symbol.source_worktree_id,
 5809                symbol.language_server_name.clone(),
 5810            )) {
 5811                *id
 5812            } else {
 5813                return Task::ready(Err(anyhow!(
 5814                    "language server for worktree and language not found"
 5815                )));
 5816            };
 5817
 5818            let worktree_abs_path = if let Some(worktree_abs_path) = self
 5819                .worktree_for_id(symbol.path.worktree_id, cx)
 5820                .map(|worktree| worktree.read(cx).abs_path())
 5821            {
 5822                worktree_abs_path
 5823            } else {
 5824                return Task::ready(Err(anyhow!("worktree not found for symbol")));
 5825            };
 5826
 5827            let symbol_abs_path = resolve_path(&worktree_abs_path, &symbol.path.path);
 5828            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
 5829                uri
 5830            } else {
 5831                return Task::ready(Err(anyhow!("invalid symbol path")));
 5832            };
 5833
 5834            self.open_local_buffer_via_lsp(
 5835                symbol_uri,
 5836                language_server_id,
 5837                symbol.language_server_name.clone(),
 5838                cx,
 5839            )
 5840        } else if let Some(project_id) = self.remote_id() {
 5841            let request = self.client.request(proto::OpenBufferForSymbol {
 5842                project_id,
 5843                symbol: Some(serialize_symbol(symbol)),
 5844            });
 5845            cx.spawn(move |this, mut cx| async move {
 5846                let response = request.await?;
 5847                let buffer_id = BufferId::new(response.buffer_id)?;
 5848                this.update(&mut cx, |this, cx| {
 5849                    this.wait_for_remote_buffer(buffer_id, cx)
 5850                })?
 5851                .await
 5852            })
 5853        } else {
 5854            Task::ready(Err(anyhow!("project does not have a remote id")))
 5855        }
 5856    }
 5857
 5858    pub fn signature_help<T: ToPointUtf16>(
 5859        &self,
 5860        buffer: &Model<Buffer>,
 5861        position: T,
 5862        cx: &mut ModelContext<Self>,
 5863    ) -> Task<Vec<SignatureHelp>> {
 5864        let position = position.to_point_utf16(buffer.read(cx));
 5865        if self.is_local_or_ssh() {
 5866            let all_actions_task = self.request_multiple_lsp_locally(
 5867                buffer,
 5868                Some(position),
 5869                GetSignatureHelp { position },
 5870                cx,
 5871            );
 5872            cx.spawn(|_, _| async move {
 5873                all_actions_task
 5874                    .await
 5875                    .into_iter()
 5876                    .flatten()
 5877                    .filter(|help| !help.markdown.is_empty())
 5878                    .collect::<Vec<_>>()
 5879            })
 5880        } else if let Some(project_id) = self.remote_id() {
 5881            let request_task = self.client().request(proto::MultiLspQuery {
 5882                buffer_id: buffer.read(cx).remote_id().into(),
 5883                version: serialize_version(&buffer.read(cx).version()),
 5884                project_id,
 5885                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5886                    proto::AllLanguageServers {},
 5887                )),
 5888                request: Some(proto::multi_lsp_query::Request::GetSignatureHelp(
 5889                    GetSignatureHelp { position }.to_proto(project_id, buffer.read(cx)),
 5890                )),
 5891            });
 5892            let buffer = buffer.clone();
 5893            cx.spawn(|weak_project, cx| async move {
 5894                let Some(project) = weak_project.upgrade() else {
 5895                    return Vec::new();
 5896                };
 5897                join_all(
 5898                    request_task
 5899                        .await
 5900                        .log_err()
 5901                        .map(|response| response.responses)
 5902                        .unwrap_or_default()
 5903                        .into_iter()
 5904                        .filter_map(|lsp_response| match lsp_response.response? {
 5905                            proto::lsp_response::Response::GetSignatureHelpResponse(response) => {
 5906                                Some(response)
 5907                            }
 5908                            unexpected => {
 5909                                debug_panic!("Unexpected response: {unexpected:?}");
 5910                                None
 5911                            }
 5912                        })
 5913                        .map(|signature_response| {
 5914                            let response = GetSignatureHelp { position }.response_from_proto(
 5915                                signature_response,
 5916                                project.clone(),
 5917                                buffer.clone(),
 5918                                cx.clone(),
 5919                            );
 5920                            async move { response.await.log_err().flatten() }
 5921                        }),
 5922                )
 5923                .await
 5924                .into_iter()
 5925                .flatten()
 5926                .collect()
 5927            })
 5928        } else {
 5929            Task::ready(Vec::new())
 5930        }
 5931    }
 5932
 5933    fn hover_impl(
 5934        &self,
 5935        buffer: &Model<Buffer>,
 5936        position: PointUtf16,
 5937        cx: &mut ModelContext<Self>,
 5938    ) -> Task<Vec<Hover>> {
 5939        if self.is_local_or_ssh() {
 5940            let all_actions_task = self.request_multiple_lsp_locally(
 5941                &buffer,
 5942                Some(position),
 5943                GetHover { position },
 5944                cx,
 5945            );
 5946            cx.spawn(|_, _| async move {
 5947                all_actions_task
 5948                    .await
 5949                    .into_iter()
 5950                    .filter_map(|hover| remove_empty_hover_blocks(hover?))
 5951                    .collect::<Vec<Hover>>()
 5952            })
 5953        } else if let Some(project_id) = self.remote_id() {
 5954            let request_task = self.client().request(proto::MultiLspQuery {
 5955                buffer_id: buffer.read(cx).remote_id().into(),
 5956                version: serialize_version(&buffer.read(cx).version()),
 5957                project_id,
 5958                strategy: Some(proto::multi_lsp_query::Strategy::All(
 5959                    proto::AllLanguageServers {},
 5960                )),
 5961                request: Some(proto::multi_lsp_query::Request::GetHover(
 5962                    GetHover { position }.to_proto(project_id, buffer.read(cx)),
 5963                )),
 5964            });
 5965            let buffer = buffer.clone();
 5966            cx.spawn(|weak_project, cx| async move {
 5967                let Some(project) = weak_project.upgrade() else {
 5968                    return Vec::new();
 5969                };
 5970                join_all(
 5971                    request_task
 5972                        .await
 5973                        .log_err()
 5974                        .map(|response| response.responses)
 5975                        .unwrap_or_default()
 5976                        .into_iter()
 5977                        .filter_map(|lsp_response| match lsp_response.response? {
 5978                            proto::lsp_response::Response::GetHoverResponse(response) => {
 5979                                Some(response)
 5980                            }
 5981                            unexpected => {
 5982                                debug_panic!("Unexpected response: {unexpected:?}");
 5983                                None
 5984                            }
 5985                        })
 5986                        .map(|hover_response| {
 5987                            let response = GetHover { position }.response_from_proto(
 5988                                hover_response,
 5989                                project.clone(),
 5990                                buffer.clone(),
 5991                                cx.clone(),
 5992                            );
 5993                            async move {
 5994                                response
 5995                                    .await
 5996                                    .log_err()
 5997                                    .flatten()
 5998                                    .and_then(remove_empty_hover_blocks)
 5999                            }
 6000                        }),
 6001                )
 6002                .await
 6003                .into_iter()
 6004                .flatten()
 6005                .collect()
 6006            })
 6007        } else {
 6008            log::error!("cannot show hovers: project does not have a remote id");
 6009            Task::ready(Vec::new())
 6010        }
 6011    }
 6012
 6013    pub fn hover<T: ToPointUtf16>(
 6014        &self,
 6015        buffer: &Model<Buffer>,
 6016        position: T,
 6017        cx: &mut ModelContext<Self>,
 6018    ) -> Task<Vec<Hover>> {
 6019        let position = position.to_point_utf16(buffer.read(cx));
 6020        self.hover_impl(buffer, position, cx)
 6021    }
 6022
 6023    fn linked_edit_impl(
 6024        &self,
 6025        buffer: &Model<Buffer>,
 6026        position: Anchor,
 6027        cx: &mut ModelContext<Self>,
 6028    ) -> Task<Result<Vec<Range<Anchor>>>> {
 6029        let snapshot = buffer.read(cx).snapshot();
 6030        let scope = snapshot.language_scope_at(position);
 6031        let Some(server_id) = self
 6032            .language_servers_for_buffer(buffer.read(cx), cx)
 6033            .filter(|(_, server)| {
 6034                server
 6035                    .capabilities()
 6036                    .linked_editing_range_provider
 6037                    .is_some()
 6038            })
 6039            .filter(|(adapter, _)| {
 6040                scope
 6041                    .as_ref()
 6042                    .map(|scope| scope.language_allowed(&adapter.name))
 6043                    .unwrap_or(true)
 6044            })
 6045            .map(|(_, server)| LanguageServerToQuery::Other(server.server_id()))
 6046            .next()
 6047            .or_else(|| {
 6048                self.is_via_collab()
 6049                    .then_some(LanguageServerToQuery::Primary)
 6050            })
 6051            .filter(|_| {
 6052                maybe!({
 6053                    let language_name = buffer.read(cx).language_at(position)?.name();
 6054                    Some(
 6055                        AllLanguageSettings::get_global(cx)
 6056                            .language(Some(&language_name))
 6057                            .linked_edits,
 6058                    )
 6059                }) == Some(true)
 6060            })
 6061        else {
 6062            return Task::ready(Ok(vec![]));
 6063        };
 6064
 6065        self.request_lsp(
 6066            buffer.clone(),
 6067            server_id,
 6068            LinkedEditingRange { position },
 6069            cx,
 6070        )
 6071    }
 6072
 6073    pub fn linked_edit(
 6074        &self,
 6075        buffer: &Model<Buffer>,
 6076        position: Anchor,
 6077        cx: &mut ModelContext<Self>,
 6078    ) -> Task<Result<Vec<Range<Anchor>>>> {
 6079        self.linked_edit_impl(buffer, position, cx)
 6080    }
 6081
 6082    #[inline(never)]
 6083    fn completions_impl(
 6084        &self,
 6085        buffer: &Model<Buffer>,
 6086        position: PointUtf16,
 6087        context: CompletionContext,
 6088        cx: &mut ModelContext<Self>,
 6089    ) -> Task<Result<Vec<Completion>>> {
 6090        let language_registry = self.languages.clone();
 6091
 6092        if self.is_local_or_ssh() {
 6093            let snapshot = buffer.read(cx).snapshot();
 6094            let offset = position.to_offset(&snapshot);
 6095            let scope = snapshot.language_scope_at(offset);
 6096            let language = snapshot.language().cloned();
 6097
 6098            let server_ids: Vec<_> = self
 6099                .language_servers_for_buffer(buffer.read(cx), cx)
 6100                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
 6101                .filter(|(adapter, _)| {
 6102                    scope
 6103                        .as_ref()
 6104                        .map(|scope| scope.language_allowed(&adapter.name))
 6105                        .unwrap_or(true)
 6106                })
 6107                .map(|(_, server)| server.server_id())
 6108                .collect();
 6109
 6110            let buffer = buffer.clone();
 6111            cx.spawn(move |this, mut cx| async move {
 6112                let mut tasks = Vec::with_capacity(server_ids.len());
 6113                this.update(&mut cx, |this, cx| {
 6114                    for server_id in server_ids {
 6115                        let lsp_adapter = this.language_server_adapter_for_id(server_id);
 6116                        tasks.push((
 6117                            lsp_adapter,
 6118                            this.request_lsp(
 6119                                buffer.clone(),
 6120                                LanguageServerToQuery::Other(server_id),
 6121                                GetCompletions {
 6122                                    position,
 6123                                    context: context.clone(),
 6124                                },
 6125                                cx,
 6126                            ),
 6127                        ));
 6128                    }
 6129                })?;
 6130
 6131                let mut completions = Vec::new();
 6132                for (lsp_adapter, task) in tasks {
 6133                    if let Ok(new_completions) = task.await {
 6134                        populate_labels_for_completions(
 6135                            new_completions,
 6136                            &language_registry,
 6137                            language.clone(),
 6138                            lsp_adapter,
 6139                            &mut completions,
 6140                        )
 6141                        .await;
 6142                    }
 6143                }
 6144
 6145                Ok(completions)
 6146            })
 6147        } else if let Some(project_id) = self.remote_id() {
 6148            let task = self.send_lsp_proto_request(
 6149                buffer.clone(),
 6150                project_id,
 6151                GetCompletions { position, context },
 6152                cx,
 6153            );
 6154            let language = buffer.read(cx).language().cloned();
 6155
 6156            // In the future, we should provide project guests with the names of LSP adapters,
 6157            // so that they can use the correct LSP adapter when computing labels. For now,
 6158            // guests just use the first LSP adapter associated with the buffer's language.
 6159            let lsp_adapter = language
 6160                .as_ref()
 6161                .and_then(|language| language_registry.lsp_adapters(language).first().cloned());
 6162
 6163            cx.foreground_executor().spawn(async move {
 6164                let completions = task.await?;
 6165                let mut result = Vec::new();
 6166                populate_labels_for_completions(
 6167                    completions,
 6168                    &language_registry,
 6169                    language,
 6170                    lsp_adapter,
 6171                    &mut result,
 6172                )
 6173                .await;
 6174                Ok(result)
 6175            })
 6176        } else {
 6177            Task::ready(Ok(Default::default()))
 6178        }
 6179    }
 6180
 6181    pub fn completions<T: ToOffset + ToPointUtf16>(
 6182        &self,
 6183        buffer: &Model<Buffer>,
 6184        position: T,
 6185        context: CompletionContext,
 6186        cx: &mut ModelContext<Self>,
 6187    ) -> Task<Result<Vec<Completion>>> {
 6188        let position = position.to_point_utf16(buffer.read(cx));
 6189        self.completions_impl(buffer, position, context, cx)
 6190    }
 6191
 6192    pub fn resolve_completions(
 6193        &self,
 6194        buffer: Model<Buffer>,
 6195        completion_indices: Vec<usize>,
 6196        completions: Arc<RwLock<Box<[Completion]>>>,
 6197        cx: &mut ModelContext<Self>,
 6198    ) -> Task<Result<bool>> {
 6199        let client = self.client();
 6200        let language_registry = self.languages().clone();
 6201
 6202        let is_remote = self.is_via_collab();
 6203        let project_id = self.remote_id();
 6204
 6205        let buffer_id = buffer.read(cx).remote_id();
 6206        let buffer_snapshot = buffer.read(cx).snapshot();
 6207
 6208        cx.spawn(move |this, mut cx| async move {
 6209            let mut did_resolve = false;
 6210            if is_remote {
 6211                let project_id =
 6212                    project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
 6213
 6214                for completion_index in completion_indices {
 6215                    let (server_id, completion) = {
 6216                        let completions_guard = completions.read();
 6217                        let completion = &completions_guard[completion_index];
 6218                        if completion.documentation.is_some() {
 6219                            continue;
 6220                        }
 6221
 6222                        did_resolve = true;
 6223                        let server_id = completion.server_id;
 6224                        let completion = completion.lsp_completion.clone();
 6225
 6226                        (server_id, completion)
 6227                    };
 6228
 6229                    Self::resolve_completion_remote(
 6230                        project_id,
 6231                        server_id,
 6232                        buffer_id,
 6233                        completions.clone(),
 6234                        completion_index,
 6235                        completion,
 6236                        client.clone(),
 6237                        language_registry.clone(),
 6238                    )
 6239                    .await;
 6240                }
 6241            } else {
 6242                for completion_index in completion_indices {
 6243                    let (server_id, completion) = {
 6244                        let completions_guard = completions.read();
 6245                        let completion = &completions_guard[completion_index];
 6246                        if completion.documentation.is_some() {
 6247                            continue;
 6248                        }
 6249
 6250                        let server_id = completion.server_id;
 6251                        let completion = completion.lsp_completion.clone();
 6252
 6253                        (server_id, completion)
 6254                    };
 6255
 6256                    let server = this
 6257                        .read_with(&mut cx, |project, _| {
 6258                            project.language_server_for_id(server_id)
 6259                        })
 6260                        .ok()
 6261                        .flatten();
 6262                    let Some(server) = server else {
 6263                        continue;
 6264                    };
 6265
 6266                    did_resolve = true;
 6267                    Self::resolve_completion_local(
 6268                        server,
 6269                        &buffer_snapshot,
 6270                        completions.clone(),
 6271                        completion_index,
 6272                        completion,
 6273                        language_registry.clone(),
 6274                    )
 6275                    .await;
 6276                }
 6277            }
 6278
 6279            Ok(did_resolve)
 6280        })
 6281    }
 6282
 6283    async fn resolve_completion_local(
 6284        server: Arc<lsp::LanguageServer>,
 6285        snapshot: &BufferSnapshot,
 6286        completions: Arc<RwLock<Box<[Completion]>>>,
 6287        completion_index: usize,
 6288        completion: lsp::CompletionItem,
 6289        language_registry: Arc<LanguageRegistry>,
 6290    ) {
 6291        let can_resolve = server
 6292            .capabilities()
 6293            .completion_provider
 6294            .as_ref()
 6295            .and_then(|options| options.resolve_provider)
 6296            .unwrap_or(false);
 6297        if !can_resolve {
 6298            return;
 6299        }
 6300
 6301        let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
 6302        let Some(completion_item) = request.await.log_err() else {
 6303            return;
 6304        };
 6305
 6306        if let Some(lsp_documentation) = completion_item.documentation.as_ref() {
 6307            let documentation = language::prepare_completion_documentation(
 6308                lsp_documentation,
 6309                &language_registry,
 6310                None, // TODO: Try to reasonably work out which language the completion is for
 6311            )
 6312            .await;
 6313
 6314            let mut completions = completions.write();
 6315            let completion = &mut completions[completion_index];
 6316            completion.documentation = Some(documentation);
 6317        } else {
 6318            let mut completions = completions.write();
 6319            let completion = &mut completions[completion_index];
 6320            completion.documentation = Some(Documentation::Undocumented);
 6321        }
 6322
 6323        if let Some(text_edit) = completion_item.text_edit.as_ref() {
 6324            // Technically we don't have to parse the whole `text_edit`, since the only
 6325            // language server we currently use that does update `text_edit` in `completionItem/resolve`
 6326            // is `typescript-language-server` and they only update `text_edit.new_text`.
 6327            // But we should not rely on that.
 6328            let edit = parse_completion_text_edit(text_edit, snapshot);
 6329
 6330            if let Some((old_range, mut new_text)) = edit {
 6331                LineEnding::normalize(&mut new_text);
 6332
 6333                let mut completions = completions.write();
 6334                let completion = &mut completions[completion_index];
 6335
 6336                completion.new_text = new_text;
 6337                completion.old_range = old_range;
 6338            }
 6339        }
 6340        if completion_item.insert_text_format == Some(InsertTextFormat::SNIPPET) {
 6341            // vtsls might change the type of completion after resolution.
 6342            let mut completions = completions.write();
 6343            let completion = &mut completions[completion_index];
 6344            if completion_item.insert_text_format != completion.lsp_completion.insert_text_format {
 6345                completion.lsp_completion.insert_text_format = completion_item.insert_text_format;
 6346            }
 6347        }
 6348    }
 6349
 6350    #[allow(clippy::too_many_arguments)]
 6351    async fn resolve_completion_remote(
 6352        project_id: u64,
 6353        server_id: LanguageServerId,
 6354        buffer_id: BufferId,
 6355        completions: Arc<RwLock<Box<[Completion]>>>,
 6356        completion_index: usize,
 6357        completion: lsp::CompletionItem,
 6358        client: Arc<Client>,
 6359        language_registry: Arc<LanguageRegistry>,
 6360    ) {
 6361        let request = proto::ResolveCompletionDocumentation {
 6362            project_id,
 6363            language_server_id: server_id.0 as u64,
 6364            lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
 6365            buffer_id: buffer_id.into(),
 6366        };
 6367
 6368        let Some(response) = client
 6369            .request(request)
 6370            .await
 6371            .context("completion documentation resolve proto request")
 6372            .log_err()
 6373        else {
 6374            return;
 6375        };
 6376
 6377        let documentation = if response.documentation.is_empty() {
 6378            Documentation::Undocumented
 6379        } else if response.documentation_is_markdown {
 6380            Documentation::MultiLineMarkdown(
 6381                markdown::parse_markdown(&response.documentation, &language_registry, None).await,
 6382            )
 6383        } else if response.documentation.lines().count() <= 1 {
 6384            Documentation::SingleLine(response.documentation)
 6385        } else {
 6386            Documentation::MultiLinePlainText(response.documentation)
 6387        };
 6388
 6389        let mut completions = completions.write();
 6390        let completion = &mut completions[completion_index];
 6391        completion.documentation = Some(documentation);
 6392
 6393        let old_range = response
 6394            .old_start
 6395            .and_then(deserialize_anchor)
 6396            .zip(response.old_end.and_then(deserialize_anchor));
 6397        if let Some((old_start, old_end)) = old_range {
 6398            if !response.new_text.is_empty() {
 6399                completion.new_text = response.new_text;
 6400                completion.old_range = old_start..old_end;
 6401            }
 6402        }
 6403    }
 6404
 6405    pub fn apply_additional_edits_for_completion(
 6406        &self,
 6407        buffer_handle: Model<Buffer>,
 6408        completion: Completion,
 6409        push_to_history: bool,
 6410        cx: &mut ModelContext<Self>,
 6411    ) -> Task<Result<Option<Transaction>>> {
 6412        let buffer = buffer_handle.read(cx);
 6413        let buffer_id = buffer.remote_id();
 6414
 6415        if self.is_local_or_ssh() {
 6416            let server_id = completion.server_id;
 6417            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
 6418                Some((_, server)) => server.clone(),
 6419                _ => return Task::ready(Ok(Default::default())),
 6420            };
 6421
 6422            cx.spawn(move |this, mut cx| async move {
 6423                let can_resolve = lang_server
 6424                    .capabilities()
 6425                    .completion_provider
 6426                    .as_ref()
 6427                    .and_then(|options| options.resolve_provider)
 6428                    .unwrap_or(false);
 6429                let additional_text_edits = if can_resolve {
 6430                    lang_server
 6431                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
 6432                        .await?
 6433                        .additional_text_edits
 6434                } else {
 6435                    completion.lsp_completion.additional_text_edits
 6436                };
 6437                if let Some(edits) = additional_text_edits {
 6438                    let edits = this
 6439                        .update(&mut cx, |this, cx| {
 6440                            this.edits_from_lsp(
 6441                                &buffer_handle,
 6442                                edits,
 6443                                lang_server.server_id(),
 6444                                None,
 6445                                cx,
 6446                            )
 6447                        })?
 6448                        .await?;
 6449
 6450                    buffer_handle.update(&mut cx, |buffer, cx| {
 6451                        buffer.finalize_last_transaction();
 6452                        buffer.start_transaction();
 6453
 6454                        for (range, text) in edits {
 6455                            let primary = &completion.old_range;
 6456                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
 6457                                && primary.end.cmp(&range.start, buffer).is_ge();
 6458                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
 6459                                && range.end.cmp(&primary.end, buffer).is_ge();
 6460
 6461                            //Skip additional edits which overlap with the primary completion edit
 6462                            //https://github.com/zed-industries/zed/pull/1871
 6463                            if !start_within && !end_within {
 6464                                buffer.edit([(range, text)], None, cx);
 6465                            }
 6466                        }
 6467
 6468                        let transaction = if buffer.end_transaction(cx).is_some() {
 6469                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6470                            if !push_to_history {
 6471                                buffer.forget_transaction(transaction.id);
 6472                            }
 6473                            Some(transaction)
 6474                        } else {
 6475                            None
 6476                        };
 6477                        Ok(transaction)
 6478                    })?
 6479                } else {
 6480                    Ok(None)
 6481                }
 6482            })
 6483        } else if let Some(project_id) = self.remote_id() {
 6484            let client = self.client.clone();
 6485            cx.spawn(move |_, mut cx| async move {
 6486                let response = client
 6487                    .request(proto::ApplyCompletionAdditionalEdits {
 6488                        project_id,
 6489                        buffer_id: buffer_id.into(),
 6490                        completion: Some(Self::serialize_completion(&CoreCompletion {
 6491                            old_range: completion.old_range,
 6492                            new_text: completion.new_text,
 6493                            server_id: completion.server_id,
 6494                            lsp_completion: completion.lsp_completion,
 6495                        })),
 6496                    })
 6497                    .await?;
 6498
 6499                if let Some(transaction) = response.transaction {
 6500                    let transaction = language::proto::deserialize_transaction(transaction)?;
 6501                    buffer_handle
 6502                        .update(&mut cx, |buffer, _| {
 6503                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 6504                        })?
 6505                        .await?;
 6506                    if push_to_history {
 6507                        buffer_handle.update(&mut cx, |buffer, _| {
 6508                            buffer.push_transaction(transaction.clone(), Instant::now());
 6509                        })?;
 6510                    }
 6511                    Ok(Some(transaction))
 6512                } else {
 6513                    Ok(None)
 6514                }
 6515            })
 6516        } else {
 6517            Task::ready(Err(anyhow!("project does not have a remote id")))
 6518        }
 6519    }
 6520
 6521    fn code_actions_impl(
 6522        &mut self,
 6523        buffer_handle: &Model<Buffer>,
 6524        range: Range<Anchor>,
 6525        cx: &mut ModelContext<Self>,
 6526    ) -> Task<Vec<CodeAction>> {
 6527        if self.is_local_or_ssh() {
 6528            let all_actions_task = self.request_multiple_lsp_locally(
 6529                &buffer_handle,
 6530                Some(range.start),
 6531                GetCodeActions {
 6532                    range: range.clone(),
 6533                    kinds: None,
 6534                },
 6535                cx,
 6536            );
 6537            cx.spawn(|_, _| async move { all_actions_task.await.into_iter().flatten().collect() })
 6538        } else if let Some(project_id) = self.remote_id() {
 6539            let request_task = self.client().request(proto::MultiLspQuery {
 6540                buffer_id: buffer_handle.read(cx).remote_id().into(),
 6541                version: serialize_version(&buffer_handle.read(cx).version()),
 6542                project_id,
 6543                strategy: Some(proto::multi_lsp_query::Strategy::All(
 6544                    proto::AllLanguageServers {},
 6545                )),
 6546                request: Some(proto::multi_lsp_query::Request::GetCodeActions(
 6547                    GetCodeActions {
 6548                        range: range.clone(),
 6549                        kinds: None,
 6550                    }
 6551                    .to_proto(project_id, buffer_handle.read(cx)),
 6552                )),
 6553            });
 6554            let buffer = buffer_handle.clone();
 6555            cx.spawn(|weak_project, cx| async move {
 6556                let Some(project) = weak_project.upgrade() else {
 6557                    return Vec::new();
 6558                };
 6559                join_all(
 6560                    request_task
 6561                        .await
 6562                        .log_err()
 6563                        .map(|response| response.responses)
 6564                        .unwrap_or_default()
 6565                        .into_iter()
 6566                        .filter_map(|lsp_response| match lsp_response.response? {
 6567                            proto::lsp_response::Response::GetCodeActionsResponse(response) => {
 6568                                Some(response)
 6569                            }
 6570                            unexpected => {
 6571                                debug_panic!("Unexpected response: {unexpected:?}");
 6572                                None
 6573                            }
 6574                        })
 6575                        .map(|code_actions_response| {
 6576                            let response = GetCodeActions {
 6577                                range: range.clone(),
 6578                                kinds: None,
 6579                            }
 6580                            .response_from_proto(
 6581                                code_actions_response,
 6582                                project.clone(),
 6583                                buffer.clone(),
 6584                                cx.clone(),
 6585                            );
 6586                            async move { response.await.log_err().unwrap_or_default() }
 6587                        }),
 6588                )
 6589                .await
 6590                .into_iter()
 6591                .flatten()
 6592                .collect()
 6593            })
 6594        } else {
 6595            log::error!("cannot fetch actions: project does not have a remote id");
 6596            Task::ready(Vec::new())
 6597        }
 6598    }
 6599
 6600    pub fn code_actions<T: Clone + ToOffset>(
 6601        &mut self,
 6602        buffer_handle: &Model<Buffer>,
 6603        range: Range<T>,
 6604        cx: &mut ModelContext<Self>,
 6605    ) -> Task<Vec<CodeAction>> {
 6606        let buffer = buffer_handle.read(cx);
 6607        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
 6608        self.code_actions_impl(buffer_handle, range, cx)
 6609    }
 6610
 6611    pub fn apply_code_action(
 6612        &self,
 6613        buffer_handle: Model<Buffer>,
 6614        mut action: CodeAction,
 6615        push_to_history: bool,
 6616        cx: &mut ModelContext<Self>,
 6617    ) -> Task<Result<ProjectTransaction>> {
 6618        if self.is_local_or_ssh() {
 6619            let buffer = buffer_handle.read(cx);
 6620            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
 6621                self.language_server_for_buffer(buffer, action.server_id, cx)
 6622            {
 6623                (adapter.clone(), server.clone())
 6624            } else {
 6625                return Task::ready(Ok(Default::default()));
 6626            };
 6627            cx.spawn(move |this, mut cx| async move {
 6628                Self::try_resolve_code_action(&lang_server, &mut action)
 6629                    .await
 6630                    .context("resolving a code action")?;
 6631                if let Some(edit) = action.lsp_action.edit {
 6632                    if edit.changes.is_some() || edit.document_changes.is_some() {
 6633                        return Self::deserialize_workspace_edit(
 6634                            this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
 6635                            edit,
 6636                            push_to_history,
 6637                            lsp_adapter.clone(),
 6638                            lang_server.clone(),
 6639                            &mut cx,
 6640                        )
 6641                        .await;
 6642                    }
 6643                }
 6644
 6645                if let Some(command) = action.lsp_action.command {
 6646                    this.update(&mut cx, |this, _| {
 6647                        this.last_workspace_edits_by_language_server
 6648                            .remove(&lang_server.server_id());
 6649                    })?;
 6650
 6651                    let result = lang_server
 6652                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 6653                            command: command.command,
 6654                            arguments: command.arguments.unwrap_or_default(),
 6655                            ..Default::default()
 6656                        })
 6657                        .await;
 6658
 6659                    if let Err(err) = result {
 6660                        // TODO: LSP ERROR
 6661                        return Err(err);
 6662                    }
 6663
 6664                    return this.update(&mut cx, |this, _| {
 6665                        this.last_workspace_edits_by_language_server
 6666                            .remove(&lang_server.server_id())
 6667                            .unwrap_or_default()
 6668                    });
 6669                }
 6670
 6671                Ok(ProjectTransaction::default())
 6672            })
 6673        } else if let Some(project_id) = self.remote_id() {
 6674            let client = self.client.clone();
 6675            let request = proto::ApplyCodeAction {
 6676                project_id,
 6677                buffer_id: buffer_handle.read(cx).remote_id().into(),
 6678                action: Some(Self::serialize_code_action(&action)),
 6679            };
 6680            cx.spawn(move |this, cx| async move {
 6681                let response = client
 6682                    .request(request)
 6683                    .await?
 6684                    .transaction
 6685                    .ok_or_else(|| anyhow!("missing transaction"))?;
 6686                Self::deserialize_project_transaction(this, response, push_to_history, cx).await
 6687            })
 6688        } else {
 6689            Task::ready(Err(anyhow!("project does not have a remote id")))
 6690        }
 6691    }
 6692
 6693    fn apply_on_type_formatting(
 6694        &self,
 6695        buffer: Model<Buffer>,
 6696        position: Anchor,
 6697        trigger: String,
 6698        cx: &mut ModelContext<Self>,
 6699    ) -> Task<Result<Option<Transaction>>> {
 6700        if self.is_local_or_ssh() {
 6701            cx.spawn(move |this, mut cx| async move {
 6702                // Do not allow multiple concurrent formatting requests for the
 6703                // same buffer.
 6704                this.update(&mut cx, |this, cx| {
 6705                    this.buffers_being_formatted
 6706                        .insert(buffer.read(cx).remote_id())
 6707                })?;
 6708
 6709                let _cleanup = defer({
 6710                    let this = this.clone();
 6711                    let mut cx = cx.clone();
 6712                    let closure_buffer = buffer.clone();
 6713                    move || {
 6714                        this.update(&mut cx, |this, cx| {
 6715                            this.buffers_being_formatted
 6716                                .remove(&closure_buffer.read(cx).remote_id());
 6717                        })
 6718                        .ok();
 6719                    }
 6720                });
 6721
 6722                buffer
 6723                    .update(&mut cx, |buffer, _| {
 6724                        buffer.wait_for_edits(Some(position.timestamp))
 6725                    })?
 6726                    .await?;
 6727                this.update(&mut cx, |this, cx| {
 6728                    let position = position.to_point_utf16(buffer.read(cx));
 6729                    this.on_type_format(buffer, position, trigger, false, cx)
 6730                })?
 6731                .await
 6732            })
 6733        } else if let Some(project_id) = self.remote_id() {
 6734            let client = self.client.clone();
 6735            let request = proto::OnTypeFormatting {
 6736                project_id,
 6737                buffer_id: buffer.read(cx).remote_id().into(),
 6738                position: Some(serialize_anchor(&position)),
 6739                trigger,
 6740                version: serialize_version(&buffer.read(cx).version()),
 6741            };
 6742            cx.spawn(move |_, _| async move {
 6743                client
 6744                    .request(request)
 6745                    .await?
 6746                    .transaction
 6747                    .map(language::proto::deserialize_transaction)
 6748                    .transpose()
 6749            })
 6750        } else {
 6751            Task::ready(Err(anyhow!("project does not have a remote id")))
 6752        }
 6753    }
 6754
 6755    async fn deserialize_edits(
 6756        this: Model<Self>,
 6757        buffer_to_edit: Model<Buffer>,
 6758        edits: Vec<lsp::TextEdit>,
 6759        push_to_history: bool,
 6760        _: Arc<CachedLspAdapter>,
 6761        language_server: Arc<LanguageServer>,
 6762        cx: &mut AsyncAppContext,
 6763    ) -> Result<Option<Transaction>> {
 6764        let edits = this
 6765            .update(cx, |this, cx| {
 6766                this.edits_from_lsp(
 6767                    &buffer_to_edit,
 6768                    edits,
 6769                    language_server.server_id(),
 6770                    None,
 6771                    cx,
 6772                )
 6773            })?
 6774            .await?;
 6775
 6776        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
 6777            buffer.finalize_last_transaction();
 6778            buffer.start_transaction();
 6779            for (range, text) in edits {
 6780                buffer.edit([(range, text)], None, cx);
 6781            }
 6782
 6783            if buffer.end_transaction(cx).is_some() {
 6784                let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6785                if !push_to_history {
 6786                    buffer.forget_transaction(transaction.id);
 6787                }
 6788                Some(transaction)
 6789            } else {
 6790                None
 6791            }
 6792        })?;
 6793
 6794        Ok(transaction)
 6795    }
 6796
 6797    async fn deserialize_workspace_edit(
 6798        this: Model<Self>,
 6799        edit: lsp::WorkspaceEdit,
 6800        push_to_history: bool,
 6801        lsp_adapter: Arc<CachedLspAdapter>,
 6802        language_server: Arc<LanguageServer>,
 6803        cx: &mut AsyncAppContext,
 6804    ) -> Result<ProjectTransaction> {
 6805        let fs = this.update(cx, |this, _| this.fs.clone())?;
 6806        let mut operations = Vec::new();
 6807        if let Some(document_changes) = edit.document_changes {
 6808            match document_changes {
 6809                lsp::DocumentChanges::Edits(edits) => {
 6810                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
 6811                }
 6812                lsp::DocumentChanges::Operations(ops) => operations = ops,
 6813            }
 6814        } else if let Some(changes) = edit.changes {
 6815            operations.extend(changes.into_iter().map(|(uri, edits)| {
 6816                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
 6817                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
 6818                        uri,
 6819                        version: None,
 6820                    },
 6821                    edits: edits.into_iter().map(Edit::Plain).collect(),
 6822                })
 6823            }));
 6824        }
 6825
 6826        let mut project_transaction = ProjectTransaction::default();
 6827        for operation in operations {
 6828            match operation {
 6829                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
 6830                    let abs_path = op
 6831                        .uri
 6832                        .to_file_path()
 6833                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6834
 6835                    if let Some(parent_path) = abs_path.parent() {
 6836                        fs.create_dir(parent_path).await?;
 6837                    }
 6838                    if abs_path.ends_with("/") {
 6839                        fs.create_dir(&abs_path).await?;
 6840                    } else {
 6841                        fs.create_file(
 6842                            &abs_path,
 6843                            op.options
 6844                                .map(|options| fs::CreateOptions {
 6845                                    overwrite: options.overwrite.unwrap_or(false),
 6846                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 6847                                })
 6848                                .unwrap_or_default(),
 6849                        )
 6850                        .await?;
 6851                    }
 6852                }
 6853
 6854                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
 6855                    let source_abs_path = op
 6856                        .old_uri
 6857                        .to_file_path()
 6858                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6859                    let target_abs_path = op
 6860                        .new_uri
 6861                        .to_file_path()
 6862                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6863                    fs.rename(
 6864                        &source_abs_path,
 6865                        &target_abs_path,
 6866                        op.options
 6867                            .map(|options| fs::RenameOptions {
 6868                                overwrite: options.overwrite.unwrap_or(false),
 6869                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
 6870                            })
 6871                            .unwrap_or_default(),
 6872                    )
 6873                    .await?;
 6874                }
 6875
 6876                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
 6877                    let abs_path = op
 6878                        .uri
 6879                        .to_file_path()
 6880                        .map_err(|_| anyhow!("can't convert URI to path"))?;
 6881                    let options = op
 6882                        .options
 6883                        .map(|options| fs::RemoveOptions {
 6884                            recursive: options.recursive.unwrap_or(false),
 6885                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
 6886                        })
 6887                        .unwrap_or_default();
 6888                    if abs_path.ends_with("/") {
 6889                        fs.remove_dir(&abs_path, options).await?;
 6890                    } else {
 6891                        fs.remove_file(&abs_path, options).await?;
 6892                    }
 6893                }
 6894
 6895                lsp::DocumentChangeOperation::Edit(op) => {
 6896                    let buffer_to_edit = this
 6897                        .update(cx, |this, cx| {
 6898                            this.open_local_buffer_via_lsp(
 6899                                op.text_document.uri.clone(),
 6900                                language_server.server_id(),
 6901                                lsp_adapter.name.clone(),
 6902                                cx,
 6903                            )
 6904                        })?
 6905                        .await?;
 6906
 6907                    let edits = this
 6908                        .update(cx, |this, cx| {
 6909                            let path = buffer_to_edit.read(cx).project_path(cx);
 6910                            let active_entry = this.active_entry;
 6911                            let is_active_entry = path.clone().map_or(false, |project_path| {
 6912                                this.entry_for_path(&project_path, cx)
 6913                                    .map_or(false, |entry| Some(entry.id) == active_entry)
 6914                            });
 6915
 6916                            let (mut edits, mut snippet_edits) = (vec![], vec![]);
 6917                            for edit in op.edits {
 6918                                match edit {
 6919                                    Edit::Plain(edit) => edits.push(edit),
 6920                                    Edit::Annotated(edit) => edits.push(edit.text_edit),
 6921                                    Edit::Snippet(edit) => {
 6922                                        let Ok(snippet) = Snippet::parse(&edit.snippet.value)
 6923                                        else {
 6924                                            continue;
 6925                                        };
 6926
 6927                                        if is_active_entry {
 6928                                            snippet_edits.push((edit.range, snippet));
 6929                                        } else {
 6930                                            // Since this buffer is not focused, apply a normal edit.
 6931                                            edits.push(TextEdit {
 6932                                                range: edit.range,
 6933                                                new_text: snippet.text,
 6934                                            });
 6935                                        }
 6936                                    }
 6937                                }
 6938                            }
 6939                            if !snippet_edits.is_empty() {
 6940                                if let Some(buffer_version) = op.text_document.version {
 6941                                    let buffer_id = buffer_to_edit.read(cx).remote_id();
 6942                                    // Check if the edit that triggered that edit has been made by this participant.
 6943                                    let should_apply_edit = this
 6944                                        .buffer_snapshots
 6945                                        .get(&buffer_id)
 6946                                        .and_then(|server_to_snapshots| {
 6947                                            let all_snapshots = server_to_snapshots
 6948                                                .get(&language_server.server_id())?;
 6949                                            all_snapshots
 6950                                                .binary_search_by_key(&buffer_version, |snapshot| {
 6951                                                    snapshot.version
 6952                                                })
 6953                                                .ok()
 6954                                                .and_then(|index| all_snapshots.get(index))
 6955                                        })
 6956                                        .map_or(false, |lsp_snapshot| {
 6957                                            let version = lsp_snapshot.snapshot.version();
 6958                                            let most_recent_edit = version
 6959                                                .iter()
 6960                                                .max_by_key(|timestamp| timestamp.value);
 6961                                            most_recent_edit.map_or(false, |edit| {
 6962                                                edit.replica_id == this.replica_id()
 6963                                            })
 6964                                        });
 6965                                    if should_apply_edit {
 6966                                        cx.emit(Event::SnippetEdit(buffer_id, snippet_edits));
 6967                                    }
 6968                                }
 6969                            }
 6970
 6971                            this.edits_from_lsp(
 6972                                &buffer_to_edit,
 6973                                edits,
 6974                                language_server.server_id(),
 6975                                op.text_document.version,
 6976                                cx,
 6977                            )
 6978                        })?
 6979                        .await?;
 6980
 6981                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
 6982                        buffer.finalize_last_transaction();
 6983                        buffer.start_transaction();
 6984                        for (range, text) in edits {
 6985                            buffer.edit([(range, text)], None, cx);
 6986                        }
 6987                        let transaction = if buffer.end_transaction(cx).is_some() {
 6988                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
 6989                            if !push_to_history {
 6990                                buffer.forget_transaction(transaction.id);
 6991                            }
 6992                            Some(transaction)
 6993                        } else {
 6994                            None
 6995                        };
 6996
 6997                        transaction
 6998                    })?;
 6999                    if let Some(transaction) = transaction {
 7000                        project_transaction.0.insert(buffer_to_edit, transaction);
 7001                    }
 7002                }
 7003            }
 7004        }
 7005
 7006        Ok(project_transaction)
 7007    }
 7008
 7009    fn prepare_rename_impl(
 7010        &mut self,
 7011        buffer: Model<Buffer>,
 7012        position: PointUtf16,
 7013        cx: &mut ModelContext<Self>,
 7014    ) -> Task<Result<Option<Range<Anchor>>>> {
 7015        self.request_lsp(
 7016            buffer,
 7017            LanguageServerToQuery::Primary,
 7018            PrepareRename { position },
 7019            cx,
 7020        )
 7021    }
 7022    pub fn prepare_rename<T: ToPointUtf16>(
 7023        &mut self,
 7024        buffer: Model<Buffer>,
 7025        position: T,
 7026        cx: &mut ModelContext<Self>,
 7027    ) -> Task<Result<Option<Range<Anchor>>>> {
 7028        let position = position.to_point_utf16(buffer.read(cx));
 7029        self.prepare_rename_impl(buffer, position, cx)
 7030    }
 7031
 7032    fn perform_rename_impl(
 7033        &mut self,
 7034        buffer: Model<Buffer>,
 7035        position: PointUtf16,
 7036        new_name: String,
 7037        push_to_history: bool,
 7038        cx: &mut ModelContext<Self>,
 7039    ) -> Task<Result<ProjectTransaction>> {
 7040        let position = position.to_point_utf16(buffer.read(cx));
 7041        self.request_lsp(
 7042            buffer,
 7043            LanguageServerToQuery::Primary,
 7044            PerformRename {
 7045                position,
 7046                new_name,
 7047                push_to_history,
 7048            },
 7049            cx,
 7050        )
 7051    }
 7052    pub fn perform_rename<T: ToPointUtf16>(
 7053        &mut self,
 7054        buffer: Model<Buffer>,
 7055        position: T,
 7056        new_name: String,
 7057        push_to_history: bool,
 7058        cx: &mut ModelContext<Self>,
 7059    ) -> Task<Result<ProjectTransaction>> {
 7060        let position = position.to_point_utf16(buffer.read(cx));
 7061        self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
 7062    }
 7063
 7064    pub fn on_type_format_impl(
 7065        &mut self,
 7066        buffer: Model<Buffer>,
 7067        position: PointUtf16,
 7068        trigger: String,
 7069        push_to_history: bool,
 7070        cx: &mut ModelContext<Self>,
 7071    ) -> Task<Result<Option<Transaction>>> {
 7072        let options = buffer.update(cx, |buffer, cx| {
 7073            lsp_command::lsp_formatting_options(language_settings(
 7074                buffer.language_at(position).as_ref(),
 7075                buffer.file(),
 7076                cx,
 7077            ))
 7078        });
 7079        self.request_lsp(
 7080            buffer.clone(),
 7081            LanguageServerToQuery::Primary,
 7082            OnTypeFormatting {
 7083                position,
 7084                trigger,
 7085                options,
 7086                push_to_history,
 7087            },
 7088            cx,
 7089        )
 7090    }
 7091
 7092    pub fn on_type_format<T: ToPointUtf16>(
 7093        &mut self,
 7094        buffer: Model<Buffer>,
 7095        position: T,
 7096        trigger: String,
 7097        push_to_history: bool,
 7098        cx: &mut ModelContext<Self>,
 7099    ) -> Task<Result<Option<Transaction>>> {
 7100        let position = position.to_point_utf16(buffer.read(cx));
 7101        self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
 7102    }
 7103
 7104    pub fn inlay_hints<T: ToOffset>(
 7105        &mut self,
 7106        buffer_handle: Model<Buffer>,
 7107        range: Range<T>,
 7108        cx: &mut ModelContext<Self>,
 7109    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 7110        let buffer = buffer_handle.read(cx);
 7111        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
 7112        self.inlay_hints_impl(buffer_handle, range, cx)
 7113    }
 7114    fn inlay_hints_impl(
 7115        &mut self,
 7116        buffer_handle: Model<Buffer>,
 7117        range: Range<Anchor>,
 7118        cx: &mut ModelContext<Self>,
 7119    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
 7120        let buffer = buffer_handle.read(cx);
 7121        let range_start = range.start;
 7122        let range_end = range.end;
 7123        let buffer_id = buffer.remote_id().into();
 7124        let lsp_request = InlayHints { range };
 7125
 7126        if self.is_local_or_ssh() {
 7127            let lsp_request_task = self.request_lsp(
 7128                buffer_handle.clone(),
 7129                LanguageServerToQuery::Primary,
 7130                lsp_request,
 7131                cx,
 7132            );
 7133            cx.spawn(move |_, mut cx| async move {
 7134                buffer_handle
 7135                    .update(&mut cx, |buffer, _| {
 7136                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
 7137                    })?
 7138                    .await
 7139                    .context("waiting for inlay hint request range edits")?;
 7140                lsp_request_task.await.context("inlay hints LSP request")
 7141            })
 7142        } else if let Some(project_id) = self.remote_id() {
 7143            let client = self.client.clone();
 7144            let request = proto::InlayHints {
 7145                project_id,
 7146                buffer_id,
 7147                start: Some(serialize_anchor(&range_start)),
 7148                end: Some(serialize_anchor(&range_end)),
 7149                version: serialize_version(&buffer_handle.read(cx).version()),
 7150            };
 7151            cx.spawn(move |project, cx| async move {
 7152                let response = client
 7153                    .request(request)
 7154                    .await
 7155                    .context("inlay hints proto request")?;
 7156                LspCommand::response_from_proto(
 7157                    lsp_request,
 7158                    response,
 7159                    project.upgrade().ok_or_else(|| anyhow!("No project"))?,
 7160                    buffer_handle.clone(),
 7161                    cx.clone(),
 7162                )
 7163                .await
 7164                .context("inlay hints proto response conversion")
 7165            })
 7166        } else {
 7167            Task::ready(Err(anyhow!("project does not have a remote id")))
 7168        }
 7169    }
 7170
 7171    pub fn resolve_inlay_hint(
 7172        &self,
 7173        hint: InlayHint,
 7174        buffer_handle: Model<Buffer>,
 7175        server_id: LanguageServerId,
 7176        cx: &mut ModelContext<Self>,
 7177    ) -> Task<anyhow::Result<InlayHint>> {
 7178        if self.is_local_or_ssh() {
 7179            let buffer = buffer_handle.read(cx);
 7180            let (_, lang_server) = if let Some((adapter, server)) =
 7181                self.language_server_for_buffer(buffer, server_id, cx)
 7182            {
 7183                (adapter.clone(), server.clone())
 7184            } else {
 7185                return Task::ready(Ok(hint));
 7186            };
 7187            if !InlayHints::can_resolve_inlays(&lang_server.capabilities()) {
 7188                return Task::ready(Ok(hint));
 7189            }
 7190
 7191            let buffer_snapshot = buffer.snapshot();
 7192            cx.spawn(move |_, mut cx| async move {
 7193                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
 7194                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
 7195                );
 7196                let resolved_hint = resolve_task
 7197                    .await
 7198                    .context("inlay hint resolve LSP request")?;
 7199                let resolved_hint = InlayHints::lsp_to_project_hint(
 7200                    resolved_hint,
 7201                    &buffer_handle,
 7202                    server_id,
 7203                    ResolveState::Resolved,
 7204                    false,
 7205                    &mut cx,
 7206                )
 7207                .await?;
 7208                Ok(resolved_hint)
 7209            })
 7210        } else if let Some(project_id) = self.remote_id() {
 7211            let client = self.client.clone();
 7212            let request = proto::ResolveInlayHint {
 7213                project_id,
 7214                buffer_id: buffer_handle.read(cx).remote_id().into(),
 7215                language_server_id: server_id.0 as u64,
 7216                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
 7217            };
 7218            cx.spawn(move |_, _| async move {
 7219                let response = client
 7220                    .request(request)
 7221                    .await
 7222                    .context("inlay hints proto request")?;
 7223                match response.hint {
 7224                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
 7225                        .context("inlay hints proto resolve response conversion"),
 7226                    None => Ok(hint),
 7227                }
 7228            })
 7229        } else {
 7230            Task::ready(Err(anyhow!("project does not have a remote id")))
 7231        }
 7232    }
 7233
 7234    pub fn search(
 7235        &mut self,
 7236        query: SearchQuery,
 7237        cx: &mut ModelContext<Self>,
 7238    ) -> Receiver<SearchResult> {
 7239        let (result_tx, result_rx) = smol::channel::unbounded();
 7240
 7241        let matching_buffers_rx =
 7242            self.search_for_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx);
 7243
 7244        cx.spawn(|_, cx| async move {
 7245            let mut range_count = 0;
 7246            let mut buffer_count = 0;
 7247            let mut limit_reached = false;
 7248            let query = Arc::new(query);
 7249            let mut chunks = matching_buffers_rx.ready_chunks(64);
 7250
 7251            // Now that we know what paths match the query, we will load at most
 7252            // 64 buffers at a time to avoid overwhelming the main thread. For each
 7253            // opened buffer, we will spawn a background task that retrieves all the
 7254            // ranges in the buffer matched by the query.
 7255            'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
 7256                let mut chunk_results = Vec::new();
 7257                for buffer in matching_buffer_chunk {
 7258                    let buffer = buffer.clone();
 7259                    let query = query.clone();
 7260                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
 7261                    chunk_results.push(cx.background_executor().spawn(async move {
 7262                        let ranges = query
 7263                            .search(&snapshot, None)
 7264                            .await
 7265                            .iter()
 7266                            .map(|range| {
 7267                                snapshot.anchor_before(range.start)
 7268                                    ..snapshot.anchor_after(range.end)
 7269                            })
 7270                            .collect::<Vec<_>>();
 7271                        anyhow::Ok((buffer, ranges))
 7272                    }));
 7273                }
 7274
 7275                let chunk_results = futures::future::join_all(chunk_results).await;
 7276                for result in chunk_results {
 7277                    if let Some((buffer, ranges)) = result.log_err() {
 7278                        range_count += ranges.len();
 7279                        buffer_count += 1;
 7280                        result_tx
 7281                            .send(SearchResult::Buffer { buffer, ranges })
 7282                            .await?;
 7283                        if buffer_count > MAX_SEARCH_RESULT_FILES
 7284                            || range_count > MAX_SEARCH_RESULT_RANGES
 7285                        {
 7286                            limit_reached = true;
 7287                            break 'outer;
 7288                        }
 7289                    }
 7290                }
 7291            }
 7292
 7293            if limit_reached {
 7294                result_tx.send(SearchResult::LimitReached).await?;
 7295            }
 7296
 7297            anyhow::Ok(())
 7298        })
 7299        .detach();
 7300
 7301        result_rx
 7302    }
 7303
 7304    fn search_for_candidate_buffers(
 7305        &mut self,
 7306        query: &SearchQuery,
 7307        limit: usize,
 7308        cx: &mut ModelContext<Project>,
 7309    ) -> Receiver<Model<Buffer>> {
 7310        if self.is_local() {
 7311            let fs = self.fs.clone();
 7312            return self.buffer_store.update(cx, |buffer_store, cx| {
 7313                buffer_store.find_search_candidates(query, limit, fs, cx)
 7314            });
 7315        } else {
 7316            self.search_for_candidate_buffers_remote(query, limit, cx)
 7317        }
 7318    }
 7319
 7320    fn search_for_candidate_buffers_remote(
 7321        &mut self,
 7322        query: &SearchQuery,
 7323        limit: usize,
 7324        cx: &mut ModelContext<Project>,
 7325    ) -> Receiver<Model<Buffer>> {
 7326        let (tx, rx) = smol::channel::unbounded();
 7327
 7328        let (client, remote_id): (AnyProtoClient, _) =
 7329            if let Some(ssh_session) = self.ssh_session.clone() {
 7330                (ssh_session.into(), 0)
 7331            } else if let Some(remote_id) = self.remote_id() {
 7332                (self.client.clone().into(), remote_id)
 7333            } else {
 7334                return rx;
 7335            };
 7336
 7337        let request = client.request(proto::FindSearchCandidates {
 7338            project_id: remote_id,
 7339            query: Some(query.to_proto()),
 7340            limit: limit as _,
 7341        });
 7342        let guard = self.retain_remotely_created_buffers(cx);
 7343
 7344        cx.spawn(move |this, mut cx| async move {
 7345            let response = request.await?;
 7346            for buffer_id in response.buffer_ids {
 7347                let buffer_id = BufferId::new(buffer_id)?;
 7348                let buffer = this
 7349                    .update(&mut cx, |this, cx| {
 7350                        this.wait_for_remote_buffer(buffer_id, cx)
 7351                    })?
 7352                    .await?;
 7353                let _ = tx.send(buffer).await;
 7354            }
 7355
 7356            drop(guard);
 7357            anyhow::Ok(())
 7358        })
 7359        .detach_and_log_err(cx);
 7360        rx
 7361    }
 7362
 7363    pub fn request_lsp<R: LspCommand>(
 7364        &self,
 7365        buffer_handle: Model<Buffer>,
 7366        server: LanguageServerToQuery,
 7367        request: R,
 7368        cx: &mut ModelContext<Self>,
 7369    ) -> Task<Result<R::Response>>
 7370    where
 7371        <R::LspRequest as lsp::request::Request>::Result: Send,
 7372        <R::LspRequest as lsp::request::Request>::Params: Send,
 7373    {
 7374        let buffer = buffer_handle.read(cx);
 7375        if self.is_local_or_ssh() {
 7376            let language_server = match server {
 7377                LanguageServerToQuery::Primary => {
 7378                    match self.primary_language_server_for_buffer(buffer, cx) {
 7379                        Some((_, server)) => Some(Arc::clone(server)),
 7380                        None => return Task::ready(Ok(Default::default())),
 7381                    }
 7382                }
 7383                LanguageServerToQuery::Other(id) => self
 7384                    .language_server_for_buffer(buffer, id, cx)
 7385                    .map(|(_, server)| Arc::clone(server)),
 7386            };
 7387            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
 7388            if let (Some(file), Some(language_server)) = (file, language_server) {
 7389                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
 7390                let status = request.status();
 7391                return cx.spawn(move |this, cx| async move {
 7392                    if !request.check_capabilities(language_server.adapter_server_capabilities()) {
 7393                        return Ok(Default::default());
 7394                    }
 7395
 7396                    let lsp_request = language_server.request::<R::LspRequest>(lsp_params);
 7397
 7398                    let id = lsp_request.id();
 7399                    let _cleanup = if status.is_some() {
 7400                        cx.update(|cx| {
 7401                            this.update(cx, |this, cx| {
 7402                                this.on_lsp_work_start(
 7403                                    language_server.server_id(),
 7404                                    id.to_string(),
 7405                                    LanguageServerProgress {
 7406                                        is_disk_based_diagnostics_progress: false,
 7407                                        is_cancellable: false,
 7408                                        title: None,
 7409                                        message: status.clone(),
 7410                                        percentage: None,
 7411                                        last_update_at: cx.background_executor().now(),
 7412                                    },
 7413                                    cx,
 7414                                );
 7415                            })
 7416                        })
 7417                        .log_err();
 7418
 7419                        Some(defer(|| {
 7420                            cx.update(|cx| {
 7421                                this.update(cx, |this, cx| {
 7422                                    this.on_lsp_work_end(
 7423                                        language_server.server_id(),
 7424                                        id.to_string(),
 7425                                        cx,
 7426                                    );
 7427                                })
 7428                            })
 7429                            .log_err();
 7430                        }))
 7431                    } else {
 7432                        None
 7433                    };
 7434
 7435                    let result = lsp_request.await;
 7436
 7437                    let response = result.map_err(|err| {
 7438                        log::warn!(
 7439                            "Generic lsp request to {} failed: {}",
 7440                            language_server.name(),
 7441                            err
 7442                        );
 7443                        err
 7444                    })?;
 7445
 7446                    request
 7447                        .response_from_lsp(
 7448                            response,
 7449                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
 7450                            buffer_handle,
 7451                            language_server.server_id(),
 7452                            cx.clone(),
 7453                        )
 7454                        .await
 7455                });
 7456            }
 7457        } else if let Some(project_id) = self.remote_id() {
 7458            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
 7459        }
 7460
 7461        Task::ready(Ok(Default::default()))
 7462    }
 7463
 7464    fn request_multiple_lsp_locally<P, R>(
 7465        &self,
 7466        buffer: &Model<Buffer>,
 7467        position: Option<P>,
 7468        request: R,
 7469        cx: &mut ModelContext<'_, Self>,
 7470    ) -> Task<Vec<R::Response>>
 7471    where
 7472        P: ToOffset,
 7473        R: LspCommand + Clone,
 7474        <R::LspRequest as lsp::request::Request>::Result: Send,
 7475        <R::LspRequest as lsp::request::Request>::Params: Send,
 7476    {
 7477        if !self.is_local_or_ssh() {
 7478            debug_panic!("Should not request multiple lsp commands in non-local project");
 7479            return Task::ready(Vec::new());
 7480        }
 7481        let snapshot = buffer.read(cx).snapshot();
 7482        let scope = position.and_then(|position| snapshot.language_scope_at(position));
 7483        let mut response_results = self
 7484            .language_servers_for_buffer(buffer.read(cx), cx)
 7485            .filter(|(adapter, _)| {
 7486                scope
 7487                    .as_ref()
 7488                    .map(|scope| scope.language_allowed(&adapter.name))
 7489                    .unwrap_or(true)
 7490            })
 7491            .map(|(_, server)| server.server_id())
 7492            .map(|server_id| {
 7493                self.request_lsp(
 7494                    buffer.clone(),
 7495                    LanguageServerToQuery::Other(server_id),
 7496                    request.clone(),
 7497                    cx,
 7498                )
 7499            })
 7500            .collect::<FuturesUnordered<_>>();
 7501
 7502        return cx.spawn(|_, _| async move {
 7503            let mut responses = Vec::with_capacity(response_results.len());
 7504            while let Some(response_result) = response_results.next().await {
 7505                if let Some(response) = response_result.log_err() {
 7506                    responses.push(response);
 7507                }
 7508            }
 7509            responses
 7510        });
 7511    }
 7512
 7513    fn send_lsp_proto_request<R: LspCommand>(
 7514        &self,
 7515        buffer: Model<Buffer>,
 7516        project_id: u64,
 7517        request: R,
 7518        cx: &mut ModelContext<'_, Project>,
 7519    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
 7520        let rpc = self.client.clone();
 7521        let message = request.to_proto(project_id, buffer.read(cx));
 7522        cx.spawn(move |this, mut cx| async move {
 7523            // Ensure the project is still alive by the time the task
 7524            // is scheduled.
 7525            this.upgrade().context("project dropped")?;
 7526            let response = rpc.request(message).await?;
 7527            let this = this.upgrade().context("project dropped")?;
 7528            if this.update(&mut cx, |this, _| this.is_disconnected())? {
 7529                Err(anyhow!("disconnected before completing request"))
 7530            } else {
 7531                request
 7532                    .response_from_proto(response, this, buffer, cx)
 7533                    .await
 7534            }
 7535        })
 7536    }
 7537
 7538    /// Move a worktree to a new position in the worktree order.
 7539    ///
 7540    /// The worktree will moved to the opposite side of the destination worktree.
 7541    ///
 7542    /// # Example
 7543    ///
 7544    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
 7545    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
 7546    ///
 7547    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
 7548    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
 7549    ///
 7550    /// # Errors
 7551    ///
 7552    /// An error will be returned if the worktree or destination worktree are not found.
 7553    pub fn move_worktree(
 7554        &mut self,
 7555        source: WorktreeId,
 7556        destination: WorktreeId,
 7557        cx: &mut ModelContext<'_, Self>,
 7558    ) -> Result<()> {
 7559        self.worktree_store.update(cx, |worktree_store, cx| {
 7560            worktree_store.move_worktree(source, destination, cx)
 7561        })
 7562    }
 7563
 7564    pub fn find_or_create_worktree(
 7565        &mut self,
 7566        abs_path: impl AsRef<Path>,
 7567        visible: bool,
 7568        cx: &mut ModelContext<Self>,
 7569    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
 7570        let abs_path = abs_path.as_ref();
 7571        if let Some((tree, relative_path)) = self.find_worktree(abs_path, cx) {
 7572            Task::ready(Ok((tree, relative_path)))
 7573        } else {
 7574            let worktree = self.create_worktree(abs_path, visible, cx);
 7575            cx.background_executor()
 7576                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
 7577        }
 7578    }
 7579
 7580    pub fn find_worktree(
 7581        &self,
 7582        abs_path: &Path,
 7583        cx: &AppContext,
 7584    ) -> Option<(Model<Worktree>, PathBuf)> {
 7585        self.worktree_store.read_with(cx, |worktree_store, cx| {
 7586            for tree in worktree_store.worktrees() {
 7587                if let Ok(relative_path) = abs_path.strip_prefix(tree.read(cx).abs_path()) {
 7588                    return Some((tree.clone(), relative_path.into()));
 7589                }
 7590            }
 7591            None
 7592        })
 7593    }
 7594
 7595    pub fn is_shared(&self) -> bool {
 7596        match &self.client_state {
 7597            ProjectClientState::Shared { .. } => true,
 7598            ProjectClientState::Local => false,
 7599            ProjectClientState::Remote { in_room, .. } => *in_room,
 7600        }
 7601    }
 7602
 7603    // Returns the resolved version of `path`, that was found in `buffer`, if it exists.
 7604    pub fn resolve_existing_file_path(
 7605        &self,
 7606        path: &str,
 7607        buffer: &Model<Buffer>,
 7608        cx: &mut ModelContext<Self>,
 7609    ) -> Task<Option<ResolvedPath>> {
 7610        // TODO: ssh based remoting.
 7611        if self.ssh_session.is_some() {
 7612            return Task::ready(None);
 7613        }
 7614
 7615        if self.is_local_or_ssh() {
 7616            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
 7617
 7618            if expanded.is_absolute() {
 7619                let fs = self.fs.clone();
 7620                cx.background_executor().spawn(async move {
 7621                    let path = expanded.as_path();
 7622                    let exists = fs.is_file(path).await;
 7623
 7624                    exists.then(|| ResolvedPath::AbsPath(expanded))
 7625                })
 7626            } else {
 7627                self.resolve_path_in_worktrees(expanded, buffer, cx)
 7628            }
 7629        } else {
 7630            let path = PathBuf::from(path);
 7631            if path.is_absolute() || path.starts_with("~") {
 7632                return Task::ready(None);
 7633            }
 7634
 7635            self.resolve_path_in_worktrees(path, buffer, cx)
 7636        }
 7637    }
 7638
 7639    fn resolve_path_in_worktrees(
 7640        &self,
 7641        path: PathBuf,
 7642        buffer: &Model<Buffer>,
 7643        cx: &mut ModelContext<Self>,
 7644    ) -> Task<Option<ResolvedPath>> {
 7645        let mut candidates = vec![path.clone()];
 7646
 7647        if let Some(file) = buffer.read(cx).file() {
 7648            if let Some(dir) = file.path().parent() {
 7649                let joined = dir.to_path_buf().join(path);
 7650                candidates.push(joined);
 7651            }
 7652        }
 7653
 7654        let worktrees = self.worktrees(cx).collect::<Vec<_>>();
 7655        cx.spawn(|_, mut cx| async move {
 7656            for worktree in worktrees {
 7657                for candidate in candidates.iter() {
 7658                    let path = worktree
 7659                        .update(&mut cx, |worktree, _| {
 7660                            let root_entry_path = &worktree.root_entry()?.path;
 7661
 7662                            let resolved = resolve_path(&root_entry_path, candidate);
 7663
 7664                            let stripped =
 7665                                resolved.strip_prefix(&root_entry_path).unwrap_or(&resolved);
 7666
 7667                            worktree.entry_for_path(stripped).map(|entry| {
 7668                                ResolvedPath::ProjectPath(ProjectPath {
 7669                                    worktree_id: worktree.id(),
 7670                                    path: entry.path.clone(),
 7671                                })
 7672                            })
 7673                        })
 7674                        .ok()?;
 7675
 7676                    if path.is_some() {
 7677                        return path;
 7678                    }
 7679                }
 7680            }
 7681            None
 7682        })
 7683    }
 7684
 7685    pub fn list_directory(
 7686        &self,
 7687        query: String,
 7688        cx: &mut ModelContext<Self>,
 7689    ) -> Task<Result<Vec<PathBuf>>> {
 7690        if self.is_local_or_ssh() {
 7691            DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
 7692        } else if let Some(dev_server) = self.dev_server_project_id().and_then(|id| {
 7693            dev_server_projects::Store::global(cx)
 7694                .read(cx)
 7695                .dev_server_for_project(id)
 7696        }) {
 7697            let request = proto::ListRemoteDirectory {
 7698                dev_server_id: dev_server.id.0,
 7699                path: query,
 7700            };
 7701            let response = self.client.request(request);
 7702            cx.background_executor().spawn(async move {
 7703                let response = response.await?;
 7704                Ok(response.entries.into_iter().map(PathBuf::from).collect())
 7705            })
 7706        } else {
 7707            Task::ready(Err(anyhow!("cannot list directory in remote project")))
 7708        }
 7709    }
 7710
 7711    fn create_worktree(
 7712        &mut self,
 7713        abs_path: impl AsRef<Path>,
 7714        visible: bool,
 7715        cx: &mut ModelContext<Self>,
 7716    ) -> Task<Result<Model<Worktree>>> {
 7717        let path: Arc<Path> = abs_path.as_ref().into();
 7718        if !self.loading_worktrees.contains_key(&path) {
 7719            let task = if self.ssh_session.is_some() {
 7720                self.create_ssh_worktree(abs_path, visible, cx)
 7721            } else if self.is_local_or_ssh() {
 7722                self.create_local_worktree(abs_path, visible, cx)
 7723            } else if self.dev_server_project_id.is_some() {
 7724                self.create_dev_server_worktree(abs_path, cx)
 7725            } else {
 7726                return Task::ready(Err(anyhow!("not a local project")));
 7727            };
 7728            self.loading_worktrees.insert(path.clone(), task.shared());
 7729        }
 7730        let task = self.loading_worktrees.get(&path).unwrap().clone();
 7731        cx.background_executor().spawn(async move {
 7732            let result = match task.await {
 7733                Ok(worktree) => Ok(worktree),
 7734                Err(err) => Err(anyhow!("{}", err)),
 7735            };
 7736            result
 7737        })
 7738    }
 7739
 7740    fn create_ssh_worktree(
 7741        &mut self,
 7742        abs_path: impl AsRef<Path>,
 7743        visible: bool,
 7744        cx: &mut ModelContext<Self>,
 7745    ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
 7746        let ssh = self.ssh_session.clone().unwrap();
 7747        let abs_path = abs_path.as_ref();
 7748        let root_name = abs_path.file_name().unwrap().to_string_lossy().to_string();
 7749        let path = abs_path.to_string_lossy().to_string();
 7750        cx.spawn(|this, mut cx| async move {
 7751            let response = ssh.request(AddWorktree { path: path.clone() }).await?;
 7752            let worktree = cx.update(|cx| {
 7753                Worktree::remote(
 7754                    0,
 7755                    0,
 7756                    proto::WorktreeMetadata {
 7757                        id: response.worktree_id,
 7758                        root_name,
 7759                        visible,
 7760                        abs_path: path,
 7761                    },
 7762                    ssh.clone().into(),
 7763                    cx,
 7764                )
 7765            })?;
 7766
 7767            this.update(&mut cx, |this, cx| this.add_worktree(&worktree, cx))?;
 7768
 7769            Ok(worktree)
 7770        })
 7771    }
 7772
 7773    fn create_local_worktree(
 7774        &mut self,
 7775        abs_path: impl AsRef<Path>,
 7776        visible: bool,
 7777        cx: &mut ModelContext<Self>,
 7778    ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
 7779        let fs = self.fs.clone();
 7780        let next_entry_id = self.next_entry_id.clone();
 7781        let path: Arc<Path> = abs_path.as_ref().into();
 7782
 7783        cx.spawn(move |project, mut cx| async move {
 7784            let worktree = Worktree::local(path.clone(), visible, fs, next_entry_id, &mut cx).await;
 7785
 7786            project.update(&mut cx, |project, _| {
 7787                project.loading_worktrees.remove(&path);
 7788            })?;
 7789
 7790            let worktree = worktree?;
 7791            project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
 7792
 7793            if visible {
 7794                cx.update(|cx| {
 7795                    cx.add_recent_document(&path);
 7796                })
 7797                .log_err();
 7798            }
 7799
 7800            Ok(worktree)
 7801        })
 7802    }
 7803
 7804    fn create_dev_server_worktree(
 7805        &mut self,
 7806        abs_path: impl AsRef<Path>,
 7807        cx: &mut ModelContext<Self>,
 7808    ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
 7809        let client = self.client.clone();
 7810        let path: Arc<Path> = abs_path.as_ref().into();
 7811        let mut paths: Vec<String> = self
 7812            .visible_worktrees(cx)
 7813            .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().to_string())
 7814            .collect();
 7815        paths.push(path.to_string_lossy().to_string());
 7816        let request = client.request(proto::UpdateDevServerProject {
 7817            dev_server_project_id: self.dev_server_project_id.unwrap().0,
 7818            paths,
 7819        });
 7820
 7821        let abs_path = abs_path.as_ref().to_path_buf();
 7822        cx.spawn(move |project, mut cx| async move {
 7823            let (tx, rx) = futures::channel::oneshot::channel();
 7824            let tx = RefCell::new(Some(tx));
 7825            let Some(project) = project.upgrade() else {
 7826                return Err(anyhow!("project dropped"))?;
 7827            };
 7828            let observer = cx.update(|cx| {
 7829                cx.observe(&project, move |project, cx| {
 7830                    let abs_path = abs_path.clone();
 7831                    project.update(cx, |project, cx| {
 7832                        if let Some((worktree, _)) = project.find_worktree(&abs_path, cx) {
 7833                            if let Some(tx) = tx.borrow_mut().take() {
 7834                                tx.send(worktree).ok();
 7835                            }
 7836                        }
 7837                    })
 7838                })
 7839            })?;
 7840
 7841            request.await?;
 7842            let worktree = rx.await.map_err(|e| anyhow!(e))?;
 7843            drop(observer);
 7844            project.update(&mut cx, |project, _| {
 7845                project.loading_worktrees.remove(&path);
 7846            })?;
 7847            Ok(worktree)
 7848        })
 7849    }
 7850
 7851    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
 7852        if let Some(dev_server_project_id) = self.dev_server_project_id {
 7853            let paths: Vec<String> = self
 7854                .visible_worktrees(cx)
 7855                .filter_map(|worktree| {
 7856                    if worktree.read(cx).id() == id_to_remove {
 7857                        None
 7858                    } else {
 7859                        Some(worktree.read(cx).abs_path().to_string_lossy().to_string())
 7860                    }
 7861                })
 7862                .collect();
 7863            if paths.len() > 0 {
 7864                let request = self.client.request(proto::UpdateDevServerProject {
 7865                    dev_server_project_id: dev_server_project_id.0,
 7866                    paths,
 7867                });
 7868                cx.background_executor()
 7869                    .spawn(request)
 7870                    .detach_and_log_err(cx);
 7871            }
 7872            return;
 7873        }
 7874        self.diagnostics.remove(&id_to_remove);
 7875        self.diagnostic_summaries.remove(&id_to_remove);
 7876        self.cached_shell_environments.remove(&id_to_remove);
 7877
 7878        let mut servers_to_remove = HashMap::default();
 7879        let mut servers_to_preserve = HashSet::default();
 7880        for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
 7881            if worktree_id == &id_to_remove {
 7882                servers_to_remove.insert(server_id, server_name.clone());
 7883            } else {
 7884                servers_to_preserve.insert(server_id);
 7885            }
 7886        }
 7887        servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
 7888        for (server_id_to_remove, server_name) in servers_to_remove {
 7889            self.language_server_ids
 7890                .remove(&(id_to_remove, server_name));
 7891            self.language_server_statuses.remove(&server_id_to_remove);
 7892            self.language_server_watched_paths
 7893                .remove(&server_id_to_remove);
 7894            self.last_workspace_edits_by_language_server
 7895                .remove(&server_id_to_remove);
 7896            self.language_servers.remove(&server_id_to_remove);
 7897            cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
 7898        }
 7899
 7900        let mut prettier_instances_to_clean = FuturesUnordered::new();
 7901        if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
 7902            for path in prettier_paths.iter().flatten() {
 7903                if let Some(prettier_instance) = self.prettier_instances.remove(path) {
 7904                    prettier_instances_to_clean.push(async move {
 7905                        prettier_instance
 7906                            .server()
 7907                            .await
 7908                            .map(|server| server.server_id())
 7909                    });
 7910                }
 7911            }
 7912        }
 7913        cx.spawn(|project, mut cx| async move {
 7914            while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
 7915                if let Some(prettier_server_id) = prettier_server_id {
 7916                    project
 7917                        .update(&mut cx, |project, cx| {
 7918                            project
 7919                                .supplementary_language_servers
 7920                                .remove(&prettier_server_id);
 7921                            cx.emit(Event::LanguageServerRemoved(prettier_server_id));
 7922                        })
 7923                        .ok();
 7924                }
 7925            }
 7926        })
 7927        .detach();
 7928
 7929        self.task_inventory().update(cx, |inventory, _| {
 7930            inventory.remove_worktree_sources(id_to_remove);
 7931        });
 7932
 7933        self.worktree_store.update(cx, |worktree_store, cx| {
 7934            worktree_store.remove_worktree(id_to_remove, cx);
 7935        });
 7936
 7937        self.metadata_changed(cx);
 7938    }
 7939
 7940    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
 7941        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
 7942        cx.subscribe(worktree, |this, worktree, event, cx| {
 7943            let is_local = worktree.read(cx).is_local();
 7944            match event {
 7945                worktree::Event::UpdatedEntries(changes) => {
 7946                    if is_local {
 7947                        this.update_local_worktree_language_servers(&worktree, changes, cx);
 7948                        this.update_local_worktree_settings(&worktree, changes, cx);
 7949                        this.update_prettier_settings(&worktree, changes, cx);
 7950                    }
 7951
 7952                    cx.emit(Event::WorktreeUpdatedEntries(
 7953                        worktree.read(cx).id(),
 7954                        changes.clone(),
 7955                    ));
 7956
 7957                    let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
 7958                    this.client()
 7959                        .telemetry()
 7960                        .report_discovered_project_events(worktree_id, changes);
 7961                }
 7962                worktree::Event::UpdatedGitRepositories(_) => {
 7963                    cx.emit(Event::WorktreeUpdatedGitRepositories);
 7964                }
 7965                worktree::Event::DeletedEntry(id) => cx.emit(Event::DeletedEntry(*id)),
 7966            }
 7967        })
 7968        .detach();
 7969
 7970        self.worktree_store.update(cx, |worktree_store, cx| {
 7971            worktree_store.add(worktree, cx);
 7972        });
 7973        self.metadata_changed(cx);
 7974    }
 7975
 7976    fn update_local_worktree_language_servers(
 7977        &mut self,
 7978        worktree_handle: &Model<Worktree>,
 7979        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
 7980        cx: &mut ModelContext<Self>,
 7981    ) {
 7982        if changes.is_empty() {
 7983            return;
 7984        }
 7985
 7986        let worktree_id = worktree_handle.read(cx).id();
 7987        let mut language_server_ids = self
 7988            .language_server_ids
 7989            .iter()
 7990            .filter_map(|((server_worktree_id, _), server_id)| {
 7991                (*server_worktree_id == worktree_id).then_some(*server_id)
 7992            })
 7993            .collect::<Vec<_>>();
 7994        language_server_ids.sort();
 7995        language_server_ids.dedup();
 7996
 7997        let abs_path = worktree_handle.read(cx).abs_path();
 7998        for server_id in &language_server_ids {
 7999            if let Some(LanguageServerState::Running { server, .. }) =
 8000                self.language_servers.get(server_id)
 8001            {
 8002                if let Some(watched_paths) = self
 8003                    .language_server_watched_paths
 8004                    .get(&server_id)
 8005                    .and_then(|paths| paths.get(&worktree_id))
 8006                {
 8007                    let params = lsp::DidChangeWatchedFilesParams {
 8008                        changes: changes
 8009                            .iter()
 8010                            .filter_map(|(path, _, change)| {
 8011                                if !watched_paths.is_match(&path) {
 8012                                    return None;
 8013                                }
 8014                                let typ = match change {
 8015                                    PathChange::Loaded => return None,
 8016                                    PathChange::Added => lsp::FileChangeType::CREATED,
 8017                                    PathChange::Removed => lsp::FileChangeType::DELETED,
 8018                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
 8019                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
 8020                                };
 8021                                Some(lsp::FileEvent {
 8022                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
 8023                                    typ,
 8024                                })
 8025                            })
 8026                            .collect(),
 8027                    };
 8028                    if !params.changes.is_empty() {
 8029                        server
 8030                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
 8031                            .log_err();
 8032                    }
 8033                }
 8034            }
 8035        }
 8036    }
 8037
 8038    fn update_local_worktree_settings(
 8039        &mut self,
 8040        worktree: &Model<Worktree>,
 8041        changes: &UpdatedEntriesSet,
 8042        cx: &mut ModelContext<Self>,
 8043    ) {
 8044        if worktree.read(cx).is_remote() {
 8045            return;
 8046        }
 8047        let project_id = self.remote_id();
 8048        let worktree_id = worktree.entity_id();
 8049        let remote_worktree_id = worktree.read(cx).id();
 8050
 8051        let mut settings_contents = Vec::new();
 8052        for (path, _, change) in changes.iter() {
 8053            let removed = change == &PathChange::Removed;
 8054            let abs_path = match worktree.read(cx).absolutize(path) {
 8055                Ok(abs_path) => abs_path,
 8056                Err(e) => {
 8057                    log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
 8058                    continue;
 8059                }
 8060            };
 8061
 8062            if path.ends_with(local_settings_file_relative_path()) {
 8063                let settings_dir = Arc::from(
 8064                    path.ancestors()
 8065                        .nth(local_settings_file_relative_path().components().count())
 8066                        .unwrap(),
 8067                );
 8068                let fs = self.fs.clone();
 8069                settings_contents.push(async move {
 8070                    (
 8071                        settings_dir,
 8072                        if removed {
 8073                            None
 8074                        } else {
 8075                            Some(async move { fs.load(&abs_path).await }.await)
 8076                        },
 8077                    )
 8078                });
 8079            } else if path.ends_with(local_tasks_file_relative_path()) {
 8080                self.task_inventory().update(cx, |task_inventory, cx| {
 8081                    if removed {
 8082                        task_inventory.remove_local_static_source(&abs_path);
 8083                    } else {
 8084                        let fs = self.fs.clone();
 8085                        let task_abs_path = abs_path.clone();
 8086                        let tasks_file_rx =
 8087                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
 8088                        task_inventory.add_source(
 8089                            TaskSourceKind::Worktree {
 8090                                id: remote_worktree_id,
 8091                                abs_path,
 8092                                id_base: "local_tasks_for_worktree".into(),
 8093                            },
 8094                            |tx, cx| StaticSource::new(TrackedFile::new(tasks_file_rx, tx, cx)),
 8095                            cx,
 8096                        );
 8097                    }
 8098                })
 8099            } else if path.ends_with(local_vscode_tasks_file_relative_path()) {
 8100                self.task_inventory().update(cx, |task_inventory, cx| {
 8101                    if removed {
 8102                        task_inventory.remove_local_static_source(&abs_path);
 8103                    } else {
 8104                        let fs = self.fs.clone();
 8105                        let task_abs_path = abs_path.clone();
 8106                        let tasks_file_rx =
 8107                            watch_config_file(&cx.background_executor(), fs, task_abs_path);
 8108                        task_inventory.add_source(
 8109                            TaskSourceKind::Worktree {
 8110                                id: remote_worktree_id,
 8111                                abs_path,
 8112                                id_base: "local_vscode_tasks_for_worktree".into(),
 8113                            },
 8114                            |tx, cx| {
 8115                                StaticSource::new(TrackedFile::new_convertible::<
 8116                                    task::VsCodeTaskFile,
 8117                                >(
 8118                                    tasks_file_rx, tx, cx
 8119                                ))
 8120                            },
 8121                            cx,
 8122                        );
 8123                    }
 8124                })
 8125            }
 8126        }
 8127
 8128        if settings_contents.is_empty() {
 8129            return;
 8130        }
 8131
 8132        let client = self.client.clone();
 8133        cx.spawn(move |_, cx| async move {
 8134            let settings_contents: Vec<(Arc<Path>, _)> =
 8135                futures::future::join_all(settings_contents).await;
 8136            cx.update(|cx| {
 8137                cx.update_global::<SettingsStore, _>(|store, cx| {
 8138                    for (directory, file_content) in settings_contents {
 8139                        let file_content = file_content.and_then(|content| content.log_err());
 8140                        store
 8141                            .set_local_settings(
 8142                                worktree_id.as_u64() as usize,
 8143                                directory.clone(),
 8144                                file_content.as_deref(),
 8145                                cx,
 8146                            )
 8147                            .log_err();
 8148                        if let Some(remote_id) = project_id {
 8149                            client
 8150                                .send(proto::UpdateWorktreeSettings {
 8151                                    project_id: remote_id,
 8152                                    worktree_id: remote_worktree_id.to_proto(),
 8153                                    path: directory.to_string_lossy().into_owned(),
 8154                                    content: file_content,
 8155                                })
 8156                                .log_err();
 8157                        }
 8158                    }
 8159                });
 8160            })
 8161            .ok();
 8162        })
 8163        .detach();
 8164    }
 8165
 8166    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
 8167        let new_active_entry = entry.and_then(|project_path| {
 8168            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 8169            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
 8170            Some(entry.id)
 8171        });
 8172        if new_active_entry != self.active_entry {
 8173            self.active_entry = new_active_entry;
 8174            cx.emit(Event::ActiveEntryChanged(new_active_entry));
 8175        }
 8176    }
 8177
 8178    pub fn language_servers_running_disk_based_diagnostics(
 8179        &self,
 8180    ) -> impl Iterator<Item = LanguageServerId> + '_ {
 8181        self.language_server_statuses
 8182            .iter()
 8183            .filter_map(|(id, status)| {
 8184                if status.has_pending_diagnostic_updates {
 8185                    Some(*id)
 8186                } else {
 8187                    None
 8188                }
 8189            })
 8190    }
 8191
 8192    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
 8193        let mut summary = DiagnosticSummary::default();
 8194        for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
 8195            summary.error_count += path_summary.error_count;
 8196            summary.warning_count += path_summary.warning_count;
 8197        }
 8198        summary
 8199    }
 8200
 8201    pub fn diagnostic_summaries<'a>(
 8202        &'a self,
 8203        include_ignored: bool,
 8204        cx: &'a AppContext,
 8205    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
 8206        self.visible_worktrees(cx)
 8207            .filter_map(|worktree| {
 8208                let worktree = worktree.read(cx);
 8209                Some((worktree, self.diagnostic_summaries.get(&worktree.id())?))
 8210            })
 8211            .flat_map(move |(worktree, summaries)| {
 8212                let worktree_id = worktree.id();
 8213                summaries
 8214                    .iter()
 8215                    .filter(move |(path, _)| {
 8216                        include_ignored
 8217                            || worktree
 8218                                .entry_for_path(path.as_ref())
 8219                                .map_or(false, |entry| !entry.is_ignored)
 8220                    })
 8221                    .flat_map(move |(path, summaries)| {
 8222                        summaries.iter().map(move |(server_id, summary)| {
 8223                            (
 8224                                ProjectPath {
 8225                                    worktree_id,
 8226                                    path: path.clone(),
 8227                                },
 8228                                *server_id,
 8229                                *summary,
 8230                            )
 8231                        })
 8232                    })
 8233            })
 8234    }
 8235
 8236    pub fn disk_based_diagnostics_started(
 8237        &mut self,
 8238        language_server_id: LanguageServerId,
 8239        cx: &mut ModelContext<Self>,
 8240    ) {
 8241        if let Some(language_server_status) =
 8242            self.language_server_statuses.get_mut(&language_server_id)
 8243        {
 8244            language_server_status.has_pending_diagnostic_updates = true;
 8245        }
 8246
 8247        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
 8248        if self.is_local_or_ssh() {
 8249            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 8250                language_server_id,
 8251                message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
 8252                    Default::default(),
 8253                ),
 8254            })
 8255            .ok();
 8256        }
 8257    }
 8258
 8259    pub fn disk_based_diagnostics_finished(
 8260        &mut self,
 8261        language_server_id: LanguageServerId,
 8262        cx: &mut ModelContext<Self>,
 8263    ) {
 8264        if let Some(language_server_status) =
 8265            self.language_server_statuses.get_mut(&language_server_id)
 8266        {
 8267            language_server_status.has_pending_diagnostic_updates = false;
 8268        }
 8269
 8270        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
 8271
 8272        if self.is_local_or_ssh() {
 8273            self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
 8274                language_server_id,
 8275                message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
 8276                    Default::default(),
 8277                ),
 8278            })
 8279            .ok();
 8280        }
 8281    }
 8282
 8283    pub fn active_entry(&self) -> Option<ProjectEntryId> {
 8284        self.active_entry
 8285    }
 8286
 8287    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
 8288        self.worktree_for_id(path.worktree_id, cx)?
 8289            .read(cx)
 8290            .entry_for_path(&path.path)
 8291            .cloned()
 8292    }
 8293
 8294    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
 8295        let worktree = self.worktree_for_entry(entry_id, cx)?;
 8296        let worktree = worktree.read(cx);
 8297        let worktree_id = worktree.id();
 8298        let path = worktree.entry_for_id(entry_id)?.path.clone();
 8299        Some(ProjectPath { worktree_id, path })
 8300    }
 8301
 8302    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
 8303        let workspace_root = self
 8304            .worktree_for_id(project_path.worktree_id, cx)?
 8305            .read(cx)
 8306            .abs_path();
 8307        let project_path = project_path.path.as_ref();
 8308
 8309        Some(if project_path == Path::new("") {
 8310            workspace_root.to_path_buf()
 8311        } else {
 8312            workspace_root.join(project_path)
 8313        })
 8314    }
 8315
 8316    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
 8317    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
 8318    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
 8319    /// the first visible worktree that has an entry for that relative path.
 8320    ///
 8321    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
 8322    /// root name from paths.
 8323    ///
 8324    /// # Arguments
 8325    ///
 8326    /// * `path` - A full path that starts with a worktree root name, or alternatively a
 8327    ///            relative path within a visible worktree.
 8328    /// * `cx` - A reference to the `AppContext`.
 8329    ///
 8330    /// # Returns
 8331    ///
 8332    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
 8333    pub fn find_project_path(&self, path: &Path, cx: &AppContext) -> Option<ProjectPath> {
 8334        let worktree_store = self.worktree_store.read(cx);
 8335
 8336        for worktree in worktree_store.visible_worktrees(cx) {
 8337            let worktree_root_name = worktree.read(cx).root_name();
 8338            if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
 8339                return Some(ProjectPath {
 8340                    worktree_id: worktree.read(cx).id(),
 8341                    path: relative_path.into(),
 8342                });
 8343            }
 8344        }
 8345
 8346        for worktree in worktree_store.visible_worktrees(cx) {
 8347            let worktree = worktree.read(cx);
 8348            if let Some(entry) = worktree.entry_for_path(path) {
 8349                return Some(ProjectPath {
 8350                    worktree_id: worktree.id(),
 8351                    path: entry.path.clone(),
 8352                });
 8353            }
 8354        }
 8355
 8356        None
 8357    }
 8358
 8359    pub fn get_workspace_root(
 8360        &self,
 8361        project_path: &ProjectPath,
 8362        cx: &AppContext,
 8363    ) -> Option<PathBuf> {
 8364        Some(
 8365            self.worktree_for_id(project_path.worktree_id, cx)?
 8366                .read(cx)
 8367                .abs_path()
 8368                .to_path_buf(),
 8369        )
 8370    }
 8371
 8372    pub fn get_repo(
 8373        &self,
 8374        project_path: &ProjectPath,
 8375        cx: &AppContext,
 8376    ) -> Option<Arc<dyn GitRepository>> {
 8377        self.worktree_for_id(project_path.worktree_id, cx)?
 8378            .read(cx)
 8379            .as_local()?
 8380            .local_git_repo(&project_path.path)
 8381    }
 8382
 8383    pub fn get_first_worktree_root_repo(&self, cx: &AppContext) -> Option<Arc<dyn GitRepository>> {
 8384        let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
 8385        let root_entry = worktree.root_git_entry()?;
 8386        worktree.get_local_repo(&root_entry)?.repo().clone().into()
 8387    }
 8388
 8389    pub fn blame_buffer(
 8390        &self,
 8391        buffer: &Model<Buffer>,
 8392        version: Option<clock::Global>,
 8393        cx: &AppContext,
 8394    ) -> Task<Result<Blame>> {
 8395        self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
 8396    }
 8397
 8398    // RPC message handlers
 8399
 8400    async fn handle_multi_lsp_query(
 8401        project: Model<Self>,
 8402        envelope: TypedEnvelope<proto::MultiLspQuery>,
 8403        mut cx: AsyncAppContext,
 8404    ) -> Result<proto::MultiLspQueryResponse> {
 8405        let sender_id = envelope.original_sender_id()?;
 8406        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8407        let version = deserialize_version(&envelope.payload.version);
 8408        let buffer = project.update(&mut cx, |project, cx| {
 8409            project.buffer_store.read(cx).get_existing(buffer_id)
 8410        })??;
 8411        buffer
 8412            .update(&mut cx, |buffer, _| {
 8413                buffer.wait_for_version(version.clone())
 8414            })?
 8415            .await?;
 8416        let buffer_version = buffer.update(&mut cx, |buffer, _| buffer.version())?;
 8417        match envelope
 8418            .payload
 8419            .strategy
 8420            .context("invalid request without the strategy")?
 8421        {
 8422            proto::multi_lsp_query::Strategy::All(_) => {
 8423                // currently, there's only one multiple language servers query strategy,
 8424                // so just ensure it's specified correctly
 8425            }
 8426        }
 8427        match envelope.payload.request {
 8428            Some(proto::multi_lsp_query::Request::GetHover(get_hover)) => {
 8429                let get_hover =
 8430                    GetHover::from_proto(get_hover, project.clone(), buffer.clone(), cx.clone())
 8431                        .await?;
 8432                let all_hovers = project
 8433                    .update(&mut cx, |project, cx| {
 8434                        project.request_multiple_lsp_locally(
 8435                            &buffer,
 8436                            Some(get_hover.position),
 8437                            get_hover,
 8438                            cx,
 8439                        )
 8440                    })?
 8441                    .await
 8442                    .into_iter()
 8443                    .filter_map(|hover| remove_empty_hover_blocks(hover?));
 8444                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8445                    responses: all_hovers
 8446                        .map(|hover| proto::LspResponse {
 8447                            response: Some(proto::lsp_response::Response::GetHoverResponse(
 8448                                GetHover::response_to_proto(
 8449                                    Some(hover),
 8450                                    project,
 8451                                    sender_id,
 8452                                    &buffer_version,
 8453                                    cx,
 8454                                ),
 8455                            )),
 8456                        })
 8457                        .collect(),
 8458                })
 8459            }
 8460            Some(proto::multi_lsp_query::Request::GetCodeActions(get_code_actions)) => {
 8461                let get_code_actions = GetCodeActions::from_proto(
 8462                    get_code_actions,
 8463                    project.clone(),
 8464                    buffer.clone(),
 8465                    cx.clone(),
 8466                )
 8467                .await?;
 8468
 8469                let all_actions = project
 8470                    .update(&mut cx, |project, cx| {
 8471                        project.request_multiple_lsp_locally(
 8472                            &buffer,
 8473                            Some(get_code_actions.range.start),
 8474                            get_code_actions,
 8475                            cx,
 8476                        )
 8477                    })?
 8478                    .await
 8479                    .into_iter();
 8480
 8481                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8482                    responses: all_actions
 8483                        .map(|code_actions| proto::LspResponse {
 8484                            response: Some(proto::lsp_response::Response::GetCodeActionsResponse(
 8485                                GetCodeActions::response_to_proto(
 8486                                    code_actions,
 8487                                    project,
 8488                                    sender_id,
 8489                                    &buffer_version,
 8490                                    cx,
 8491                                ),
 8492                            )),
 8493                        })
 8494                        .collect(),
 8495                })
 8496            }
 8497            Some(proto::multi_lsp_query::Request::GetSignatureHelp(get_signature_help)) => {
 8498                let get_signature_help = GetSignatureHelp::from_proto(
 8499                    get_signature_help,
 8500                    project.clone(),
 8501                    buffer.clone(),
 8502                    cx.clone(),
 8503                )
 8504                .await?;
 8505
 8506                let all_signatures = project
 8507                    .update(&mut cx, |project, cx| {
 8508                        project.request_multiple_lsp_locally(
 8509                            &buffer,
 8510                            Some(get_signature_help.position),
 8511                            get_signature_help,
 8512                            cx,
 8513                        )
 8514                    })?
 8515                    .await
 8516                    .into_iter();
 8517
 8518                project.update(&mut cx, |project, cx| proto::MultiLspQueryResponse {
 8519                    responses: all_signatures
 8520                        .map(|signature_help| proto::LspResponse {
 8521                            response: Some(
 8522                                proto::lsp_response::Response::GetSignatureHelpResponse(
 8523                                    GetSignatureHelp::response_to_proto(
 8524                                        signature_help,
 8525                                        project,
 8526                                        sender_id,
 8527                                        &buffer_version,
 8528                                        cx,
 8529                                    ),
 8530                                ),
 8531                            ),
 8532                        })
 8533                        .collect(),
 8534                })
 8535            }
 8536            None => anyhow::bail!("empty multi lsp query request"),
 8537        }
 8538    }
 8539
 8540    async fn handle_unshare_project(
 8541        this: Model<Self>,
 8542        _: TypedEnvelope<proto::UnshareProject>,
 8543        mut cx: AsyncAppContext,
 8544    ) -> Result<()> {
 8545        this.update(&mut cx, |this, cx| {
 8546            if this.is_local_or_ssh() {
 8547                this.unshare(cx)?;
 8548            } else {
 8549                this.disconnected_from_host(cx);
 8550            }
 8551            Ok(())
 8552        })?
 8553    }
 8554
 8555    async fn handle_add_collaborator(
 8556        this: Model<Self>,
 8557        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
 8558        mut cx: AsyncAppContext,
 8559    ) -> Result<()> {
 8560        let collaborator = envelope
 8561            .payload
 8562            .collaborator
 8563            .take()
 8564            .ok_or_else(|| anyhow!("empty collaborator"))?;
 8565
 8566        let collaborator = Collaborator::from_proto(collaborator)?;
 8567        this.update(&mut cx, |this, cx| {
 8568            this.buffer_store.update(cx, |buffer_store, _| {
 8569                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
 8570            });
 8571            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
 8572            this.collaborators
 8573                .insert(collaborator.peer_id, collaborator);
 8574            cx.notify();
 8575        })?;
 8576
 8577        Ok(())
 8578    }
 8579
 8580    async fn handle_update_project_collaborator(
 8581        this: Model<Self>,
 8582        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
 8583        mut cx: AsyncAppContext,
 8584    ) -> Result<()> {
 8585        let old_peer_id = envelope
 8586            .payload
 8587            .old_peer_id
 8588            .ok_or_else(|| anyhow!("missing old peer id"))?;
 8589        let new_peer_id = envelope
 8590            .payload
 8591            .new_peer_id
 8592            .ok_or_else(|| anyhow!("missing new peer id"))?;
 8593        this.update(&mut cx, |this, cx| {
 8594            let collaborator = this
 8595                .collaborators
 8596                .remove(&old_peer_id)
 8597                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
 8598            let is_host = collaborator.replica_id == 0;
 8599            this.collaborators.insert(new_peer_id, collaborator);
 8600
 8601            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
 8602            this.buffer_store.update(cx, |buffer_store, _| {
 8603                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
 8604            });
 8605
 8606            if is_host {
 8607                this.buffer_store
 8608                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
 8609                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
 8610                    .unwrap();
 8611                cx.emit(Event::HostReshared);
 8612            }
 8613
 8614            cx.emit(Event::CollaboratorUpdated {
 8615                old_peer_id,
 8616                new_peer_id,
 8617            });
 8618            cx.notify();
 8619            Ok(())
 8620        })?
 8621    }
 8622
 8623    async fn handle_remove_collaborator(
 8624        this: Model<Self>,
 8625        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
 8626        mut cx: AsyncAppContext,
 8627    ) -> Result<()> {
 8628        this.update(&mut cx, |this, cx| {
 8629            let peer_id = envelope
 8630                .payload
 8631                .peer_id
 8632                .ok_or_else(|| anyhow!("invalid peer id"))?;
 8633            let replica_id = this
 8634                .collaborators
 8635                .remove(&peer_id)
 8636                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
 8637                .replica_id;
 8638            this.buffer_store.update(cx, |buffer_store, cx| {
 8639                buffer_store.forget_shared_buffers_for(&peer_id);
 8640                for buffer in buffer_store.buffers() {
 8641                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
 8642                }
 8643            });
 8644
 8645            cx.emit(Event::CollaboratorLeft(peer_id));
 8646            cx.notify();
 8647            Ok(())
 8648        })?
 8649    }
 8650
 8651    async fn handle_update_project(
 8652        this: Model<Self>,
 8653        envelope: TypedEnvelope<proto::UpdateProject>,
 8654        mut cx: AsyncAppContext,
 8655    ) -> Result<()> {
 8656        this.update(&mut cx, |this, cx| {
 8657            // Don't handle messages that were sent before the response to us joining the project
 8658            if envelope.message_id > this.join_project_response_message_id {
 8659                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
 8660            }
 8661            Ok(())
 8662        })?
 8663    }
 8664
 8665    async fn handle_update_worktree(
 8666        this: Model<Self>,
 8667        envelope: TypedEnvelope<proto::UpdateWorktree>,
 8668        mut cx: AsyncAppContext,
 8669    ) -> Result<()> {
 8670        this.update(&mut cx, |this, cx| {
 8671            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8672            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8673                worktree.update(cx, |worktree, _| {
 8674                    let worktree = worktree.as_remote_mut().unwrap();
 8675                    worktree.update_from_remote(envelope.payload);
 8676                });
 8677            }
 8678            Ok(())
 8679        })?
 8680    }
 8681
 8682    async fn handle_update_worktree_settings(
 8683        this: Model<Self>,
 8684        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
 8685        mut cx: AsyncAppContext,
 8686    ) -> Result<()> {
 8687        this.update(&mut cx, |this, cx| {
 8688            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8689            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
 8690                cx.update_global::<SettingsStore, _>(|store, cx| {
 8691                    store
 8692                        .set_local_settings(
 8693                            worktree.entity_id().as_u64() as usize,
 8694                            PathBuf::from(&envelope.payload.path).into(),
 8695                            envelope.payload.content.as_deref(),
 8696                            cx,
 8697                        )
 8698                        .log_err();
 8699                });
 8700            }
 8701            Ok(())
 8702        })?
 8703    }
 8704
 8705    async fn handle_update_diagnostic_summary(
 8706        this: Model<Self>,
 8707        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 8708        mut cx: AsyncAppContext,
 8709    ) -> Result<()> {
 8710        this.update(&mut cx, |this, cx| {
 8711            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 8712            if let Some(message) = envelope.payload.summary {
 8713                let project_path = ProjectPath {
 8714                    worktree_id,
 8715                    path: Path::new(&message.path).into(),
 8716                };
 8717                let path = project_path.path.clone();
 8718                let server_id = LanguageServerId(message.language_server_id as usize);
 8719                let summary = DiagnosticSummary {
 8720                    error_count: message.error_count as usize,
 8721                    warning_count: message.warning_count as usize,
 8722                };
 8723
 8724                if summary.is_empty() {
 8725                    if let Some(worktree_summaries) =
 8726                        this.diagnostic_summaries.get_mut(&worktree_id)
 8727                    {
 8728                        if let Some(summaries) = worktree_summaries.get_mut(&path) {
 8729                            summaries.remove(&server_id);
 8730                            if summaries.is_empty() {
 8731                                worktree_summaries.remove(&path);
 8732                            }
 8733                        }
 8734                    }
 8735                } else {
 8736                    this.diagnostic_summaries
 8737                        .entry(worktree_id)
 8738                        .or_default()
 8739                        .entry(path)
 8740                        .or_default()
 8741                        .insert(server_id, summary);
 8742                }
 8743                cx.emit(Event::DiagnosticsUpdated {
 8744                    language_server_id: LanguageServerId(message.language_server_id as usize),
 8745                    path: project_path,
 8746                });
 8747            }
 8748            Ok(())
 8749        })?
 8750    }
 8751
 8752    async fn handle_start_language_server(
 8753        this: Model<Self>,
 8754        envelope: TypedEnvelope<proto::StartLanguageServer>,
 8755        mut cx: AsyncAppContext,
 8756    ) -> Result<()> {
 8757        let server = envelope
 8758            .payload
 8759            .server
 8760            .ok_or_else(|| anyhow!("invalid server"))?;
 8761        this.update(&mut cx, |this, cx| {
 8762            this.language_server_statuses.insert(
 8763                LanguageServerId(server.id as usize),
 8764                LanguageServerStatus {
 8765                    name: server.name,
 8766                    pending_work: Default::default(),
 8767                    has_pending_diagnostic_updates: false,
 8768                    progress_tokens: Default::default(),
 8769                },
 8770            );
 8771            cx.notify();
 8772        })?;
 8773        Ok(())
 8774    }
 8775
 8776    async fn handle_update_language_server(
 8777        this: Model<Self>,
 8778        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
 8779        mut cx: AsyncAppContext,
 8780    ) -> Result<()> {
 8781        this.update(&mut cx, |this, cx| {
 8782            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
 8783
 8784            match envelope
 8785                .payload
 8786                .variant
 8787                .ok_or_else(|| anyhow!("invalid variant"))?
 8788            {
 8789                proto::update_language_server::Variant::WorkStart(payload) => {
 8790                    this.on_lsp_work_start(
 8791                        language_server_id,
 8792                        payload.token,
 8793                        LanguageServerProgress {
 8794                            title: payload.title,
 8795                            is_disk_based_diagnostics_progress: false,
 8796                            is_cancellable: false,
 8797                            message: payload.message,
 8798                            percentage: payload.percentage.map(|p| p as usize),
 8799                            last_update_at: cx.background_executor().now(),
 8800                        },
 8801                        cx,
 8802                    );
 8803                }
 8804
 8805                proto::update_language_server::Variant::WorkProgress(payload) => {
 8806                    this.on_lsp_work_progress(
 8807                        language_server_id,
 8808                        payload.token,
 8809                        LanguageServerProgress {
 8810                            title: None,
 8811                            is_disk_based_diagnostics_progress: false,
 8812                            is_cancellable: false,
 8813                            message: payload.message,
 8814                            percentage: payload.percentage.map(|p| p as usize),
 8815                            last_update_at: cx.background_executor().now(),
 8816                        },
 8817                        cx,
 8818                    );
 8819                }
 8820
 8821                proto::update_language_server::Variant::WorkEnd(payload) => {
 8822                    this.on_lsp_work_end(language_server_id, payload.token, cx);
 8823                }
 8824
 8825                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
 8826                    this.disk_based_diagnostics_started(language_server_id, cx);
 8827                }
 8828
 8829                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
 8830                    this.disk_based_diagnostics_finished(language_server_id, cx)
 8831                }
 8832            }
 8833
 8834            Ok(())
 8835        })?
 8836    }
 8837
 8838    async fn handle_update_buffer(
 8839        this: Model<Self>,
 8840        envelope: TypedEnvelope<proto::UpdateBuffer>,
 8841        cx: AsyncAppContext,
 8842    ) -> Result<proto::Ack> {
 8843        let buffer_store = this.read_with(&cx, |this, cx| {
 8844            if let Some(ssh) = &this.ssh_session {
 8845                let mut payload = envelope.payload.clone();
 8846                payload.project_id = 0;
 8847                cx.background_executor()
 8848                    .spawn(ssh.request(payload))
 8849                    .detach_and_log_err(cx);
 8850            }
 8851            this.buffer_store.clone()
 8852        })?;
 8853        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
 8854    }
 8855
 8856    fn retain_remotely_created_buffers(
 8857        &mut self,
 8858        cx: &mut ModelContext<Self>,
 8859    ) -> RemotelyCreatedBufferGuard {
 8860        {
 8861            let mut remotely_created_buffers = self.remotely_created_buffers.lock();
 8862            if remotely_created_buffers.retain_count == 0 {
 8863                remotely_created_buffers.buffers = self.buffer_store.read(cx).buffers().collect();
 8864            }
 8865            remotely_created_buffers.retain_count += 1;
 8866        }
 8867        RemotelyCreatedBufferGuard {
 8868            remote_buffers: Arc::downgrade(&self.remotely_created_buffers),
 8869        }
 8870    }
 8871
 8872    async fn handle_create_buffer_for_peer(
 8873        this: Model<Self>,
 8874        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
 8875        mut cx: AsyncAppContext,
 8876    ) -> Result<()> {
 8877        this.update(&mut cx, |this, cx| {
 8878            this.buffer_store.update(cx, |buffer_store, cx| {
 8879                buffer_store.handle_create_buffer_for_peer(
 8880                    envelope,
 8881                    this.replica_id(),
 8882                    this.capability(),
 8883                    cx,
 8884                )
 8885            })
 8886        })?
 8887    }
 8888
 8889    async fn handle_reload_buffers(
 8890        this: Model<Self>,
 8891        envelope: TypedEnvelope<proto::ReloadBuffers>,
 8892        mut cx: AsyncAppContext,
 8893    ) -> Result<proto::ReloadBuffersResponse> {
 8894        let sender_id = envelope.original_sender_id()?;
 8895        let reload = this.update(&mut cx, |this, cx| {
 8896            let mut buffers = HashSet::default();
 8897            for buffer_id in &envelope.payload.buffer_ids {
 8898                let buffer_id = BufferId::new(*buffer_id)?;
 8899                buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
 8900            }
 8901            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
 8902        })??;
 8903
 8904        let project_transaction = reload.await?;
 8905        let project_transaction = this.update(&mut cx, |this, cx| {
 8906            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 8907        })?;
 8908        Ok(proto::ReloadBuffersResponse {
 8909            transaction: Some(project_transaction),
 8910        })
 8911    }
 8912
 8913    async fn handle_synchronize_buffers(
 8914        this: Model<Self>,
 8915        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
 8916        mut cx: AsyncAppContext,
 8917    ) -> Result<proto::SynchronizeBuffersResponse> {
 8918        let response = this.update(&mut cx, |this, cx| {
 8919            let client = this.client.clone();
 8920            this.buffer_store.update(cx, |this, cx| {
 8921                this.handle_synchronize_buffers(envelope, cx, client)
 8922            })
 8923        })??;
 8924
 8925        Ok(response)
 8926    }
 8927
 8928    async fn handle_format_buffers(
 8929        this: Model<Self>,
 8930        envelope: TypedEnvelope<proto::FormatBuffers>,
 8931        mut cx: AsyncAppContext,
 8932    ) -> Result<proto::FormatBuffersResponse> {
 8933        let sender_id = envelope.original_sender_id()?;
 8934        let format = this.update(&mut cx, |this, cx| {
 8935            let mut buffers = HashSet::default();
 8936            for buffer_id in &envelope.payload.buffer_ids {
 8937                let buffer_id = BufferId::new(*buffer_id)?;
 8938                buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
 8939            }
 8940            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
 8941            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
 8942        })??;
 8943
 8944        let project_transaction = format.await?;
 8945        let project_transaction = this.update(&mut cx, |this, cx| {
 8946            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 8947        })?;
 8948        Ok(proto::FormatBuffersResponse {
 8949            transaction: Some(project_transaction),
 8950        })
 8951    }
 8952
 8953    async fn handle_apply_additional_edits_for_completion(
 8954        this: Model<Self>,
 8955        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
 8956        mut cx: AsyncAppContext,
 8957    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
 8958        let (buffer, completion) = this.update(&mut cx, |this, cx| {
 8959            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 8960            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 8961            let completion = Self::deserialize_completion(
 8962                envelope
 8963                    .payload
 8964                    .completion
 8965                    .ok_or_else(|| anyhow!("invalid completion"))?,
 8966            )?;
 8967            anyhow::Ok((buffer, completion))
 8968        })??;
 8969
 8970        let apply_additional_edits = this.update(&mut cx, |this, cx| {
 8971            this.apply_additional_edits_for_completion(
 8972                buffer,
 8973                Completion {
 8974                    old_range: completion.old_range,
 8975                    new_text: completion.new_text,
 8976                    lsp_completion: completion.lsp_completion,
 8977                    server_id: completion.server_id,
 8978                    documentation: None,
 8979                    label: CodeLabel {
 8980                        text: Default::default(),
 8981                        runs: Default::default(),
 8982                        filter_range: Default::default(),
 8983                    },
 8984                    confirm: None,
 8985                },
 8986                false,
 8987                cx,
 8988            )
 8989        })?;
 8990
 8991        Ok(proto::ApplyCompletionAdditionalEditsResponse {
 8992            transaction: apply_additional_edits
 8993                .await?
 8994                .as_ref()
 8995                .map(language::proto::serialize_transaction),
 8996        })
 8997    }
 8998
 8999    async fn handle_resolve_completion_documentation(
 9000        this: Model<Self>,
 9001        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
 9002        mut cx: AsyncAppContext,
 9003    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
 9004        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
 9005
 9006        let completion = this
 9007            .read_with(&mut cx, |this, _| {
 9008                let id = LanguageServerId(envelope.payload.language_server_id as usize);
 9009                let Some(server) = this.language_server_for_id(id) else {
 9010                    return Err(anyhow!("No language server {id}"));
 9011                };
 9012
 9013                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
 9014            })??
 9015            .await?;
 9016
 9017        let mut documentation_is_markdown = false;
 9018        let documentation = match completion.documentation {
 9019            Some(lsp::Documentation::String(text)) => text,
 9020
 9021            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
 9022                documentation_is_markdown = kind == lsp::MarkupKind::Markdown;
 9023                value
 9024            }
 9025
 9026            _ => String::new(),
 9027        };
 9028
 9029        // If we have a new buffer_id, that means we're talking to a new client
 9030        // and want to check for new text_edits in the completion too.
 9031        let mut old_start = None;
 9032        let mut old_end = None;
 9033        let mut new_text = String::default();
 9034        if let Ok(buffer_id) = BufferId::new(envelope.payload.buffer_id) {
 9035            let buffer_snapshot = this.update(&mut cx, |this, cx| {
 9036                let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 9037                anyhow::Ok(buffer.read(cx).snapshot())
 9038            })??;
 9039
 9040            if let Some(text_edit) = completion.text_edit.as_ref() {
 9041                let edit = parse_completion_text_edit(text_edit, &buffer_snapshot);
 9042
 9043                if let Some((old_range, mut text_edit_new_text)) = edit {
 9044                    LineEnding::normalize(&mut text_edit_new_text);
 9045
 9046                    new_text = text_edit_new_text;
 9047                    old_start = Some(serialize_anchor(&old_range.start));
 9048                    old_end = Some(serialize_anchor(&old_range.end));
 9049                }
 9050            }
 9051        }
 9052
 9053        Ok(proto::ResolveCompletionDocumentationResponse {
 9054            documentation,
 9055            documentation_is_markdown,
 9056            old_start,
 9057            old_end,
 9058            new_text,
 9059        })
 9060    }
 9061
 9062    async fn handle_apply_code_action(
 9063        this: Model<Self>,
 9064        envelope: TypedEnvelope<proto::ApplyCodeAction>,
 9065        mut cx: AsyncAppContext,
 9066    ) -> Result<proto::ApplyCodeActionResponse> {
 9067        let sender_id = envelope.original_sender_id()?;
 9068        let action = Self::deserialize_code_action(
 9069            envelope
 9070                .payload
 9071                .action
 9072                .ok_or_else(|| anyhow!("invalid action"))?,
 9073        )?;
 9074        let apply_code_action = this.update(&mut cx, |this, cx| {
 9075            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9076            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 9077            anyhow::Ok(this.apply_code_action(buffer, action, false, cx))
 9078        })??;
 9079
 9080        let project_transaction = apply_code_action.await?;
 9081        let project_transaction = this.update(&mut cx, |this, cx| {
 9082            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
 9083        })?;
 9084        Ok(proto::ApplyCodeActionResponse {
 9085            transaction: Some(project_transaction),
 9086        })
 9087    }
 9088
 9089    async fn handle_on_type_formatting(
 9090        this: Model<Self>,
 9091        envelope: TypedEnvelope<proto::OnTypeFormatting>,
 9092        mut cx: AsyncAppContext,
 9093    ) -> Result<proto::OnTypeFormattingResponse> {
 9094        let on_type_formatting = this.update(&mut cx, |this, cx| {
 9095            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9096            let buffer = this.buffer_store.read(cx).get_existing(buffer_id)?;
 9097            let position = envelope
 9098                .payload
 9099                .position
 9100                .and_then(deserialize_anchor)
 9101                .ok_or_else(|| anyhow!("invalid position"))?;
 9102            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
 9103                buffer,
 9104                position,
 9105                envelope.payload.trigger.clone(),
 9106                cx,
 9107            ))
 9108        })??;
 9109
 9110        let transaction = on_type_formatting
 9111            .await?
 9112            .as_ref()
 9113            .map(language::proto::serialize_transaction);
 9114        Ok(proto::OnTypeFormattingResponse { transaction })
 9115    }
 9116
 9117    async fn handle_inlay_hints(
 9118        this: Model<Self>,
 9119        envelope: TypedEnvelope<proto::InlayHints>,
 9120        mut cx: AsyncAppContext,
 9121    ) -> Result<proto::InlayHintsResponse> {
 9122        let sender_id = envelope.original_sender_id()?;
 9123        let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9124        let buffer = this.update(&mut cx, |this, cx| {
 9125            this.buffer_store.read(cx).get_existing(buffer_id)
 9126        })??;
 9127        buffer
 9128            .update(&mut cx, |buffer, _| {
 9129                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
 9130            })?
 9131            .await
 9132            .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
 9133
 9134        let start = envelope
 9135            .payload
 9136            .start
 9137            .and_then(deserialize_anchor)
 9138            .context("missing range start")?;
 9139        let end = envelope
 9140            .payload
 9141            .end
 9142            .and_then(deserialize_anchor)
 9143            .context("missing range end")?;
 9144        let buffer_hints = this
 9145            .update(&mut cx, |project, cx| {
 9146                project.inlay_hints(buffer.clone(), start..end, cx)
 9147            })?
 9148            .await
 9149            .context("inlay hints fetch")?;
 9150
 9151        this.update(&mut cx, |project, cx| {
 9152            InlayHints::response_to_proto(
 9153                buffer_hints,
 9154                project,
 9155                sender_id,
 9156                &buffer.read(cx).version(),
 9157                cx,
 9158            )
 9159        })
 9160    }
 9161
 9162    async fn handle_resolve_inlay_hint(
 9163        this: Model<Self>,
 9164        envelope: TypedEnvelope<proto::ResolveInlayHint>,
 9165        mut cx: AsyncAppContext,
 9166    ) -> Result<proto::ResolveInlayHintResponse> {
 9167        let proto_hint = envelope
 9168            .payload
 9169            .hint
 9170            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
 9171        let hint = InlayHints::proto_to_project_hint(proto_hint)
 9172            .context("resolved proto inlay hint conversion")?;
 9173        let buffer = this.update(&mut cx, |this, cx| {
 9174            let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
 9175            this.buffer_store.read(cx).get_existing(buffer_id)
 9176        })??;
 9177        let response_hint = this
 9178            .update(&mut cx, |project, cx| {
 9179                project.resolve_inlay_hint(
 9180                    hint,
 9181                    buffer,
 9182                    LanguageServerId(envelope.payload.language_server_id as usize),
 9183                    cx,
 9184                )
 9185            })?
 9186            .await
 9187            .context("inlay hints fetch")?;
 9188        Ok(proto::ResolveInlayHintResponse {
 9189            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
 9190        })
 9191    }
 9192
 9193    async fn handle_task_context_for_location(
 9194        project: Model<Self>,
 9195        envelope: TypedEnvelope<proto::TaskContextForLocation>,
 9196        mut cx: AsyncAppContext,
 9197    ) -> Result<proto::TaskContext> {
 9198        let location = envelope
 9199            .payload
 9200            .location
 9201            .context("no location given for task context handling")?;
 9202        let location = cx
 9203            .update(|cx| deserialize_location(&project, location, cx))?
 9204            .await?;
 9205        let context_task = project.update(&mut cx, |project, cx| {
 9206            let captured_variables = {
 9207                let mut variables = TaskVariables::default();
 9208                for range in location
 9209                    .buffer
 9210                    .read(cx)
 9211                    .snapshot()
 9212                    .runnable_ranges(location.range.clone())
 9213                {
 9214                    for (capture_name, value) in range.extra_captures {
 9215                        variables.insert(VariableName::Custom(capture_name.into()), value);
 9216                    }
 9217                }
 9218                variables
 9219            };
 9220            project.task_context_for_location(captured_variables, location, cx)
 9221        })?;
 9222        let task_context = context_task.await.unwrap_or_default();
 9223        Ok(proto::TaskContext {
 9224            project_env: task_context.project_env.into_iter().collect(),
 9225            cwd: task_context
 9226                .cwd
 9227                .map(|cwd| cwd.to_string_lossy().to_string()),
 9228            task_variables: task_context
 9229                .task_variables
 9230                .into_iter()
 9231                .map(|(variable_name, variable_value)| (variable_name.to_string(), variable_value))
 9232                .collect(),
 9233        })
 9234    }
 9235
 9236    async fn handle_task_templates(
 9237        project: Model<Self>,
 9238        envelope: TypedEnvelope<proto::TaskTemplates>,
 9239        mut cx: AsyncAppContext,
 9240    ) -> Result<proto::TaskTemplatesResponse> {
 9241        let worktree = envelope.payload.worktree_id.map(WorktreeId::from_proto);
 9242        let location = match envelope.payload.location {
 9243            Some(location) => Some(
 9244                cx.update(|cx| deserialize_location(&project, location, cx))?
 9245                    .await
 9246                    .context("task templates request location deserializing")?,
 9247            ),
 9248            None => None,
 9249        };
 9250
 9251        let templates = project
 9252            .update(&mut cx, |project, cx| {
 9253                project.task_templates(worktree, location, cx)
 9254            })?
 9255            .await
 9256            .context("receiving task templates")?
 9257            .into_iter()
 9258            .map(|(kind, template)| {
 9259                let kind = Some(match kind {
 9260                    TaskSourceKind::UserInput => proto::task_source_kind::Kind::UserInput(
 9261                        proto::task_source_kind::UserInput {},
 9262                    ),
 9263                    TaskSourceKind::Worktree {
 9264                        id,
 9265                        abs_path,
 9266                        id_base,
 9267                    } => {
 9268                        proto::task_source_kind::Kind::Worktree(proto::task_source_kind::Worktree {
 9269                            id: id.to_proto(),
 9270                            abs_path: abs_path.to_string_lossy().to_string(),
 9271                            id_base: id_base.to_string(),
 9272                        })
 9273                    }
 9274                    TaskSourceKind::AbsPath { id_base, abs_path } => {
 9275                        proto::task_source_kind::Kind::AbsPath(proto::task_source_kind::AbsPath {
 9276                            abs_path: abs_path.to_string_lossy().to_string(),
 9277                            id_base: id_base.to_string(),
 9278                        })
 9279                    }
 9280                    TaskSourceKind::Language { name } => {
 9281                        proto::task_source_kind::Kind::Language(proto::task_source_kind::Language {
 9282                            name: name.to_string(),
 9283                        })
 9284                    }
 9285                });
 9286                let kind = Some(proto::TaskSourceKind { kind });
 9287                let template = Some(proto::TaskTemplate {
 9288                    label: template.label,
 9289                    command: template.command,
 9290                    args: template.args,
 9291                    env: template.env.into_iter().collect(),
 9292                    cwd: template.cwd,
 9293                    use_new_terminal: template.use_new_terminal,
 9294                    allow_concurrent_runs: template.allow_concurrent_runs,
 9295                    reveal: match template.reveal {
 9296                        RevealStrategy::Always => proto::RevealStrategy::RevealAlways as i32,
 9297                        RevealStrategy::Never => proto::RevealStrategy::RevealNever as i32,
 9298                    },
 9299                    hide: match template.hide {
 9300                        HideStrategy::Always => proto::HideStrategy::HideAlways as i32,
 9301                        HideStrategy::Never => proto::HideStrategy::HideNever as i32,
 9302                        HideStrategy::OnSuccess => proto::HideStrategy::HideOnSuccess as i32,
 9303                    },
 9304                    shell: Some(proto::Shell {
 9305                        shell_type: Some(match template.shell {
 9306                            Shell::System => proto::shell::ShellType::System(proto::System {}),
 9307                            Shell::Program(program) => proto::shell::ShellType::Program(program),
 9308                            Shell::WithArguments { program, args } => {
 9309                                proto::shell::ShellType::WithArguments(
 9310                                    proto::shell::WithArguments { program, args },
 9311                                )
 9312                            }
 9313                        }),
 9314                    }),
 9315                    tags: template.tags,
 9316                });
 9317                proto::TemplatePair { kind, template }
 9318            })
 9319            .collect();
 9320
 9321        Ok(proto::TaskTemplatesResponse { templates })
 9322    }
 9323
 9324    async fn try_resolve_code_action(
 9325        lang_server: &LanguageServer,
 9326        action: &mut CodeAction,
 9327    ) -> anyhow::Result<()> {
 9328        if GetCodeActions::can_resolve_actions(&lang_server.capabilities()) {
 9329            if action.lsp_action.data.is_some()
 9330                && (action.lsp_action.command.is_none() || action.lsp_action.edit.is_none())
 9331            {
 9332                action.lsp_action = lang_server
 9333                    .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action.clone())
 9334                    .await?;
 9335            }
 9336        }
 9337
 9338        anyhow::Ok(())
 9339    }
 9340
 9341    async fn execute_code_actions_on_servers(
 9342        project: &WeakModel<Project>,
 9343        adapters_and_servers: &Vec<(Arc<CachedLspAdapter>, Arc<LanguageServer>)>,
 9344        code_actions: Vec<lsp::CodeActionKind>,
 9345        buffer: &Model<Buffer>,
 9346        push_to_history: bool,
 9347        project_transaction: &mut ProjectTransaction,
 9348        cx: &mut AsyncAppContext,
 9349    ) -> Result<(), anyhow::Error> {
 9350        for (lsp_adapter, language_server) in adapters_and_servers.iter() {
 9351            let code_actions = code_actions.clone();
 9352
 9353            let actions = project
 9354                .update(cx, move |this, cx| {
 9355                    let request = GetCodeActions {
 9356                        range: text::Anchor::MIN..text::Anchor::MAX,
 9357                        kinds: Some(code_actions),
 9358                    };
 9359                    let server = LanguageServerToQuery::Other(language_server.server_id());
 9360                    this.request_lsp(buffer.clone(), server, request, cx)
 9361                })?
 9362                .await?;
 9363
 9364            for mut action in actions {
 9365                Self::try_resolve_code_action(&language_server, &mut action)
 9366                    .await
 9367                    .context("resolving a formatting code action")?;
 9368
 9369                if let Some(edit) = action.lsp_action.edit {
 9370                    if edit.changes.is_none() && edit.document_changes.is_none() {
 9371                        continue;
 9372                    }
 9373
 9374                    let new = Self::deserialize_workspace_edit(
 9375                        project
 9376                            .upgrade()
 9377                            .ok_or_else(|| anyhow!("project dropped"))?,
 9378                        edit,
 9379                        push_to_history,
 9380                        lsp_adapter.clone(),
 9381                        language_server.clone(),
 9382                        cx,
 9383                    )
 9384                    .await?;
 9385                    project_transaction.0.extend(new.0);
 9386                }
 9387
 9388                if let Some(command) = action.lsp_action.command {
 9389                    project.update(cx, |this, _| {
 9390                        this.last_workspace_edits_by_language_server
 9391                            .remove(&language_server.server_id());
 9392                    })?;
 9393
 9394                    language_server
 9395                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
 9396                            command: command.command,
 9397                            arguments: command.arguments.unwrap_or_default(),
 9398                            ..Default::default()
 9399                        })
 9400                        .await?;
 9401
 9402                    project.update(cx, |this, _| {
 9403                        project_transaction.0.extend(
 9404                            this.last_workspace_edits_by_language_server
 9405                                .remove(&language_server.server_id())
 9406                                .unwrap_or_default()
 9407                                .0,
 9408                        )
 9409                    })?;
 9410                }
 9411            }
 9412        }
 9413
 9414        Ok(())
 9415    }
 9416
 9417    async fn handle_refresh_inlay_hints(
 9418        this: Model<Self>,
 9419        _: TypedEnvelope<proto::RefreshInlayHints>,
 9420        mut cx: AsyncAppContext,
 9421    ) -> Result<proto::Ack> {
 9422        this.update(&mut cx, |_, cx| {
 9423            cx.emit(Event::RefreshInlayHints);
 9424        })?;
 9425        Ok(proto::Ack {})
 9426    }
 9427
 9428    async fn handle_lsp_command<T: LspCommand>(
 9429        this: Model<Self>,
 9430        envelope: TypedEnvelope<T::ProtoRequest>,
 9431        mut cx: AsyncAppContext,
 9432    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
 9433    where
 9434        <T::LspRequest as lsp::request::Request>::Params: Send,
 9435        <T::LspRequest as lsp::request::Request>::Result: Send,
 9436    {
 9437        let sender_id = envelope.original_sender_id()?;
 9438        let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
 9439        let buffer_handle = this.update(&mut cx, |this, cx| {
 9440            this.buffer_store.read(cx).get_existing(buffer_id)
 9441        })??;
 9442        let request = T::from_proto(
 9443            envelope.payload,
 9444            this.clone(),
 9445            buffer_handle.clone(),
 9446            cx.clone(),
 9447        )
 9448        .await?;
 9449        let response = this
 9450            .update(&mut cx, |this, cx| {
 9451                this.request_lsp(
 9452                    buffer_handle.clone(),
 9453                    LanguageServerToQuery::Primary,
 9454                    request,
 9455                    cx,
 9456                )
 9457            })?
 9458            .await?;
 9459        this.update(&mut cx, |this, cx| {
 9460            Ok(T::response_to_proto(
 9461                response,
 9462                this,
 9463                sender_id,
 9464                &buffer_handle.read(cx).version(),
 9465                cx,
 9466            ))
 9467        })?
 9468    }
 9469
 9470    async fn handle_get_project_symbols(
 9471        this: Model<Self>,
 9472        envelope: TypedEnvelope<proto::GetProjectSymbols>,
 9473        mut cx: AsyncAppContext,
 9474    ) -> Result<proto::GetProjectSymbolsResponse> {
 9475        let symbols = this
 9476            .update(&mut cx, |this, cx| {
 9477                this.symbols(&envelope.payload.query, cx)
 9478            })?
 9479            .await?;
 9480
 9481        Ok(proto::GetProjectSymbolsResponse {
 9482            symbols: symbols.iter().map(serialize_symbol).collect(),
 9483        })
 9484    }
 9485
 9486    async fn handle_search_project(
 9487        this: Model<Self>,
 9488        envelope: TypedEnvelope<proto::SearchProject>,
 9489        mut cx: AsyncAppContext,
 9490    ) -> Result<proto::SearchProjectResponse> {
 9491        let peer_id = envelope.original_sender_id()?;
 9492        let query = SearchQuery::from_proto_v1(envelope.payload)?;
 9493        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
 9494
 9495        cx.spawn(move |mut cx| async move {
 9496            let mut locations = Vec::new();
 9497            let mut limit_reached = false;
 9498            while let Some(result) = result.next().await {
 9499                match result {
 9500                    SearchResult::Buffer { buffer, ranges } => {
 9501                        for range in ranges {
 9502                            let start = serialize_anchor(&range.start);
 9503                            let end = serialize_anchor(&range.end);
 9504                            let buffer_id = this.update(&mut cx, |this, cx| {
 9505                                this.create_buffer_for_peer(&buffer, peer_id, cx).into()
 9506                            })?;
 9507                            locations.push(proto::Location {
 9508                                buffer_id,
 9509                                start: Some(start),
 9510                                end: Some(end),
 9511                            });
 9512                        }
 9513                    }
 9514                    SearchResult::LimitReached => limit_reached = true,
 9515                }
 9516            }
 9517            Ok(proto::SearchProjectResponse {
 9518                locations,
 9519                limit_reached,
 9520                // will restart
 9521            })
 9522        })
 9523        .await
 9524    }
 9525
 9526    async fn handle_search_candidate_buffers(
 9527        this: Model<Self>,
 9528        envelope: TypedEnvelope<proto::FindSearchCandidates>,
 9529        mut cx: AsyncAppContext,
 9530    ) -> Result<proto::FindSearchCandidatesResponse> {
 9531        let peer_id = envelope.original_sender_id()?;
 9532        let message = envelope.payload;
 9533        let query = SearchQuery::from_proto(
 9534            message
 9535                .query
 9536                .ok_or_else(|| anyhow!("missing query field"))?,
 9537        )?;
 9538        let mut results = this.update(&mut cx, |this, cx| {
 9539            this.search_for_candidate_buffers(&query, message.limit as _, cx)
 9540        })?;
 9541
 9542        let mut response = proto::FindSearchCandidatesResponse {
 9543            buffer_ids: Vec::new(),
 9544        };
 9545
 9546        while let Some(buffer) = results.next().await {
 9547            this.update(&mut cx, |this, cx| {
 9548                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
 9549                response.buffer_ids.push(buffer_id.to_proto());
 9550            })?;
 9551        }
 9552
 9553        Ok(response)
 9554    }
 9555
 9556    async fn handle_open_buffer_for_symbol(
 9557        this: Model<Self>,
 9558        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
 9559        mut cx: AsyncAppContext,
 9560    ) -> Result<proto::OpenBufferForSymbolResponse> {
 9561        let peer_id = envelope.original_sender_id()?;
 9562        let symbol = envelope
 9563            .payload
 9564            .symbol
 9565            .ok_or_else(|| anyhow!("invalid symbol"))?;
 9566        let symbol = Self::deserialize_symbol(symbol)?;
 9567        let symbol = this.update(&mut cx, |this, _| {
 9568            let signature = this.symbol_signature(&symbol.path);
 9569            if signature == symbol.signature {
 9570                Ok(symbol)
 9571            } else {
 9572                Err(anyhow!("invalid symbol signature"))
 9573            }
 9574        })??;
 9575        let buffer = this
 9576            .update(&mut cx, |this, cx| {
 9577                this.open_buffer_for_symbol(
 9578                    &Symbol {
 9579                        language_server_name: symbol.language_server_name,
 9580                        source_worktree_id: symbol.source_worktree_id,
 9581                        path: symbol.path,
 9582                        name: symbol.name,
 9583                        kind: symbol.kind,
 9584                        range: symbol.range,
 9585                        signature: symbol.signature,
 9586                        label: CodeLabel {
 9587                            text: Default::default(),
 9588                            runs: Default::default(),
 9589                            filter_range: Default::default(),
 9590                        },
 9591                    },
 9592                    cx,
 9593                )
 9594            })?
 9595            .await?;
 9596
 9597        this.update(&mut cx, |this, cx| {
 9598            let is_private = buffer
 9599                .read(cx)
 9600                .file()
 9601                .map(|f| f.is_private())
 9602                .unwrap_or_default();
 9603            if is_private {
 9604                Err(anyhow!(ErrorCode::UnsharedItem))
 9605            } else {
 9606                Ok(proto::OpenBufferForSymbolResponse {
 9607                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9608                })
 9609            }
 9610        })?
 9611    }
 9612
 9613    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
 9614        let mut hasher = Sha256::new();
 9615        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
 9616        hasher.update(project_path.path.to_string_lossy().as_bytes());
 9617        hasher.update(self.nonce.to_be_bytes());
 9618        hasher.finalize().as_slice().try_into().unwrap()
 9619    }
 9620
 9621    async fn handle_open_buffer_by_id(
 9622        this: Model<Self>,
 9623        envelope: TypedEnvelope<proto::OpenBufferById>,
 9624        mut cx: AsyncAppContext,
 9625    ) -> Result<proto::OpenBufferResponse> {
 9626        let peer_id = envelope.original_sender_id()?;
 9627        let buffer_id = BufferId::new(envelope.payload.id)?;
 9628        let buffer = this
 9629            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
 9630            .await?;
 9631        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9632    }
 9633
 9634    async fn handle_open_buffer_by_path(
 9635        this: Model<Self>,
 9636        envelope: TypedEnvelope<proto::OpenBufferByPath>,
 9637        mut cx: AsyncAppContext,
 9638    ) -> Result<proto::OpenBufferResponse> {
 9639        let peer_id = envelope.original_sender_id()?;
 9640        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 9641        let open_buffer = this.update(&mut cx, |this, cx| {
 9642            this.open_buffer(
 9643                ProjectPath {
 9644                    worktree_id,
 9645                    path: PathBuf::from(envelope.payload.path).into(),
 9646                },
 9647                cx,
 9648            )
 9649        })?;
 9650
 9651        let buffer = open_buffer.await?;
 9652        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9653    }
 9654
 9655    async fn handle_open_new_buffer(
 9656        this: Model<Self>,
 9657        envelope: TypedEnvelope<proto::OpenNewBuffer>,
 9658        mut cx: AsyncAppContext,
 9659    ) -> Result<proto::OpenBufferResponse> {
 9660        let buffer = this.update(&mut cx, |this, cx| this.create_local_buffer("", None, cx))?;
 9661        let peer_id = envelope.original_sender_id()?;
 9662
 9663        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
 9664    }
 9665
 9666    fn respond_to_open_buffer_request(
 9667        this: Model<Self>,
 9668        buffer: Model<Buffer>,
 9669        peer_id: proto::PeerId,
 9670        cx: &mut AsyncAppContext,
 9671    ) -> Result<proto::OpenBufferResponse> {
 9672        this.update(cx, |this, cx| {
 9673            let is_private = buffer
 9674                .read(cx)
 9675                .file()
 9676                .map(|f| f.is_private())
 9677                .unwrap_or_default();
 9678            if is_private {
 9679                Err(anyhow!(ErrorCode::UnsharedItem))
 9680            } else {
 9681                Ok(proto::OpenBufferResponse {
 9682                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
 9683                })
 9684            }
 9685        })?
 9686    }
 9687
 9688    fn serialize_project_transaction_for_peer(
 9689        &mut self,
 9690        project_transaction: ProjectTransaction,
 9691        peer_id: proto::PeerId,
 9692        cx: &mut AppContext,
 9693    ) -> proto::ProjectTransaction {
 9694        let mut serialized_transaction = proto::ProjectTransaction {
 9695            buffer_ids: Default::default(),
 9696            transactions: Default::default(),
 9697        };
 9698        for (buffer, transaction) in project_transaction.0 {
 9699            serialized_transaction
 9700                .buffer_ids
 9701                .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
 9702            serialized_transaction
 9703                .transactions
 9704                .push(language::proto::serialize_transaction(&transaction));
 9705        }
 9706        serialized_transaction
 9707    }
 9708
 9709    async fn deserialize_project_transaction(
 9710        this: WeakModel<Self>,
 9711        message: proto::ProjectTransaction,
 9712        push_to_history: bool,
 9713        mut cx: AsyncAppContext,
 9714    ) -> Result<ProjectTransaction> {
 9715        let mut project_transaction = ProjectTransaction::default();
 9716        for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions) {
 9717            let buffer_id = BufferId::new(buffer_id)?;
 9718            let buffer = this
 9719                .update(&mut cx, |this, cx| {
 9720                    this.wait_for_remote_buffer(buffer_id, cx)
 9721                })?
 9722                .await?;
 9723            let transaction = language::proto::deserialize_transaction(transaction)?;
 9724            project_transaction.0.insert(buffer, transaction);
 9725        }
 9726
 9727        for (buffer, transaction) in &project_transaction.0 {
 9728            buffer
 9729                .update(&mut cx, |buffer, _| {
 9730                    buffer.wait_for_edits(transaction.edit_ids.iter().copied())
 9731                })?
 9732                .await?;
 9733
 9734            if push_to_history {
 9735                buffer.update(&mut cx, |buffer, _| {
 9736                    buffer.push_transaction(transaction.clone(), Instant::now());
 9737                })?;
 9738            }
 9739        }
 9740
 9741        Ok(project_transaction)
 9742    }
 9743
 9744    fn create_buffer_for_peer(
 9745        &mut self,
 9746        buffer: &Model<Buffer>,
 9747        peer_id: proto::PeerId,
 9748        cx: &mut AppContext,
 9749    ) -> BufferId {
 9750        if let Some(project_id) = self.remote_id() {
 9751            self.buffer_store
 9752                .update(cx, |buffer_store, cx| {
 9753                    buffer_store.create_buffer_for_peer(
 9754                        buffer,
 9755                        peer_id,
 9756                        project_id,
 9757                        self.client.clone().into(),
 9758                        cx,
 9759                    )
 9760                })
 9761                .detach_and_log_err(cx);
 9762        }
 9763        buffer.read(cx).remote_id()
 9764    }
 9765
 9766    fn wait_for_remote_buffer(
 9767        &mut self,
 9768        id: BufferId,
 9769        cx: &mut ModelContext<Self>,
 9770    ) -> Task<Result<Model<Buffer>>> {
 9771        self.buffer_store.update(cx, |buffer_store, cx| {
 9772            buffer_store.wait_for_remote_buffer(id, cx)
 9773        })
 9774    }
 9775
 9776    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 9777        let project_id = match self.client_state {
 9778            ProjectClientState::Remote {
 9779                sharing_has_stopped,
 9780                remote_id,
 9781                ..
 9782            } => {
 9783                if sharing_has_stopped {
 9784                    return Task::ready(Err(anyhow!(
 9785                        "can't synchronize remote buffers on a readonly project"
 9786                    )));
 9787                } else {
 9788                    remote_id
 9789                }
 9790            }
 9791            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
 9792                return Task::ready(Err(anyhow!(
 9793                    "can't synchronize remote buffers on a local project"
 9794                )))
 9795            }
 9796        };
 9797
 9798        let client = self.client.clone();
 9799        cx.spawn(move |this, mut cx| async move {
 9800            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
 9801                this.buffer_store.read(cx).buffer_version_info(cx)
 9802            })?;
 9803            let response = client
 9804                .request(proto::SynchronizeBuffers {
 9805                    project_id,
 9806                    buffers,
 9807                })
 9808                .await?;
 9809
 9810            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
 9811                response
 9812                    .buffers
 9813                    .into_iter()
 9814                    .map(|buffer| {
 9815                        let client = client.clone();
 9816                        let buffer_id = match BufferId::new(buffer.id) {
 9817                            Ok(id) => id,
 9818                            Err(e) => {
 9819                                return Task::ready(Err(e));
 9820                            }
 9821                        };
 9822                        let remote_version = language::proto::deserialize_version(&buffer.version);
 9823                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
 9824                            let operations =
 9825                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
 9826                            cx.background_executor().spawn(async move {
 9827                                let operations = operations.await;
 9828                                for chunk in split_operations(operations) {
 9829                                    client
 9830                                        .request(proto::UpdateBuffer {
 9831                                            project_id,
 9832                                            buffer_id: buffer_id.into(),
 9833                                            operations: chunk,
 9834                                        })
 9835                                        .await?;
 9836                                }
 9837                                anyhow::Ok(())
 9838                            })
 9839                        } else {
 9840                            Task::ready(Ok(()))
 9841                        }
 9842                    })
 9843                    .collect::<Vec<_>>()
 9844            })?;
 9845
 9846            // Any incomplete buffers have open requests waiting. Request that the host sends
 9847            // creates these buffers for us again to unblock any waiting futures.
 9848            for id in incomplete_buffer_ids {
 9849                cx.background_executor()
 9850                    .spawn(client.request(proto::OpenBufferById {
 9851                        project_id,
 9852                        id: id.into(),
 9853                    }))
 9854                    .detach();
 9855            }
 9856
 9857            futures::future::join_all(send_updates_for_buffers)
 9858                .await
 9859                .into_iter()
 9860                .collect()
 9861        })
 9862    }
 9863
 9864    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
 9865        self.worktrees(cx)
 9866            .map(|worktree| {
 9867                let worktree = worktree.read(cx);
 9868                proto::WorktreeMetadata {
 9869                    id: worktree.id().to_proto(),
 9870                    root_name: worktree.root_name().into(),
 9871                    visible: worktree.is_visible(),
 9872                    abs_path: worktree.abs_path().to_string_lossy().into(),
 9873                }
 9874            })
 9875            .collect()
 9876    }
 9877
 9878    fn set_worktrees_from_proto(
 9879        &mut self,
 9880        worktrees: Vec<proto::WorktreeMetadata>,
 9881        cx: &mut ModelContext<Project>,
 9882    ) -> Result<()> {
 9883        self.metadata_changed(cx);
 9884        self.worktree_store.update(cx, |worktree_store, cx| {
 9885            worktree_store.set_worktrees_from_proto(
 9886                worktrees,
 9887                self.replica_id(),
 9888                self.remote_id().ok_or_else(|| anyhow!("invalid project"))?,
 9889                self.client.clone().into(),
 9890                cx,
 9891            )
 9892        })
 9893    }
 9894
 9895    fn set_collaborators_from_proto(
 9896        &mut self,
 9897        messages: Vec<proto::Collaborator>,
 9898        cx: &mut ModelContext<Self>,
 9899    ) -> Result<()> {
 9900        let mut collaborators = HashMap::default();
 9901        for message in messages {
 9902            let collaborator = Collaborator::from_proto(message)?;
 9903            collaborators.insert(collaborator.peer_id, collaborator);
 9904        }
 9905        for old_peer_id in self.collaborators.keys() {
 9906            if !collaborators.contains_key(old_peer_id) {
 9907                cx.emit(Event::CollaboratorLeft(*old_peer_id));
 9908            }
 9909        }
 9910        self.collaborators = collaborators;
 9911        Ok(())
 9912    }
 9913
 9914    fn deserialize_symbol(serialized_symbol: proto::Symbol) -> Result<CoreSymbol> {
 9915        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
 9916        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
 9917        let kind = unsafe { mem::transmute::<i32, lsp::SymbolKind>(serialized_symbol.kind) };
 9918        let path = ProjectPath {
 9919            worktree_id,
 9920            path: PathBuf::from(serialized_symbol.path).into(),
 9921        };
 9922
 9923        let start = serialized_symbol
 9924            .start
 9925            .ok_or_else(|| anyhow!("invalid start"))?;
 9926        let end = serialized_symbol
 9927            .end
 9928            .ok_or_else(|| anyhow!("invalid end"))?;
 9929        Ok(CoreSymbol {
 9930            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
 9931            source_worktree_id,
 9932            path,
 9933            name: serialized_symbol.name,
 9934            range: Unclipped(PointUtf16::new(start.row, start.column))
 9935                ..Unclipped(PointUtf16::new(end.row, end.column)),
 9936            kind,
 9937            signature: serialized_symbol
 9938                .signature
 9939                .try_into()
 9940                .map_err(|_| anyhow!("invalid signature"))?,
 9941        })
 9942    }
 9943
 9944    fn serialize_completion(completion: &CoreCompletion) -> proto::Completion {
 9945        proto::Completion {
 9946            old_start: Some(serialize_anchor(&completion.old_range.start)),
 9947            old_end: Some(serialize_anchor(&completion.old_range.end)),
 9948            new_text: completion.new_text.clone(),
 9949            server_id: completion.server_id.0 as u64,
 9950            lsp_completion: serde_json::to_vec(&completion.lsp_completion).unwrap(),
 9951        }
 9952    }
 9953
 9954    fn deserialize_completion(completion: proto::Completion) -> Result<CoreCompletion> {
 9955        let old_start = completion
 9956            .old_start
 9957            .and_then(deserialize_anchor)
 9958            .ok_or_else(|| anyhow!("invalid old start"))?;
 9959        let old_end = completion
 9960            .old_end
 9961            .and_then(deserialize_anchor)
 9962            .ok_or_else(|| anyhow!("invalid old end"))?;
 9963        let lsp_completion = serde_json::from_slice(&completion.lsp_completion)?;
 9964
 9965        Ok(CoreCompletion {
 9966            old_range: old_start..old_end,
 9967            new_text: completion.new_text,
 9968            server_id: LanguageServerId(completion.server_id as usize),
 9969            lsp_completion,
 9970        })
 9971    }
 9972
 9973    fn serialize_code_action(action: &CodeAction) -> proto::CodeAction {
 9974        proto::CodeAction {
 9975            server_id: action.server_id.0 as u64,
 9976            start: Some(serialize_anchor(&action.range.start)),
 9977            end: Some(serialize_anchor(&action.range.end)),
 9978            lsp_action: serde_json::to_vec(&action.lsp_action).unwrap(),
 9979        }
 9980    }
 9981
 9982    fn deserialize_code_action(action: proto::CodeAction) -> Result<CodeAction> {
 9983        let start = action
 9984            .start
 9985            .and_then(deserialize_anchor)
 9986            .ok_or_else(|| anyhow!("invalid start"))?;
 9987        let end = action
 9988            .end
 9989            .and_then(deserialize_anchor)
 9990            .ok_or_else(|| anyhow!("invalid end"))?;
 9991        let lsp_action = serde_json::from_slice(&action.lsp_action)?;
 9992        Ok(CodeAction {
 9993            server_id: LanguageServerId(action.server_id as usize),
 9994            range: start..end,
 9995            lsp_action,
 9996        })
 9997    }
 9998
 9999    #[allow(clippy::type_complexity)]
10000    fn edits_from_lsp(
10001        &mut self,
10002        buffer: &Model<Buffer>,
10003        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
10004        server_id: LanguageServerId,
10005        version: Option<i32>,
10006        cx: &mut ModelContext<Self>,
10007    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
10008        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
10009        cx.background_executor().spawn(async move {
10010            let snapshot = snapshot?;
10011            let mut lsp_edits = lsp_edits
10012                .into_iter()
10013                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
10014                .collect::<Vec<_>>();
10015            lsp_edits.sort_by_key(|(range, _)| range.start);
10016
10017            let mut lsp_edits = lsp_edits.into_iter().peekable();
10018            let mut edits = Vec::new();
10019            while let Some((range, mut new_text)) = lsp_edits.next() {
10020                // Clip invalid ranges provided by the language server.
10021                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
10022                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
10023
10024                // Combine any LSP edits that are adjacent.
10025                //
10026                // Also, combine LSP edits that are separated from each other by only
10027                // a newline. This is important because for some code actions,
10028                // Rust-analyzer rewrites the entire buffer via a series of edits that
10029                // are separated by unchanged newline characters.
10030                //
10031                // In order for the diffing logic below to work properly, any edits that
10032                // cancel each other out must be combined into one.
10033                while let Some((next_range, next_text)) = lsp_edits.peek() {
10034                    if next_range.start.0 > range.end {
10035                        if next_range.start.0.row > range.end.row + 1
10036                            || next_range.start.0.column > 0
10037                            || snapshot.clip_point_utf16(
10038                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
10039                                Bias::Left,
10040                            ) > range.end
10041                        {
10042                            break;
10043                        }
10044                        new_text.push('\n');
10045                    }
10046                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
10047                    new_text.push_str(next_text);
10048                    lsp_edits.next();
10049                }
10050
10051                // For multiline edits, perform a diff of the old and new text so that
10052                // we can identify the changes more precisely, preserving the locations
10053                // of any anchors positioned in the unchanged regions.
10054                if range.end.row > range.start.row {
10055                    let mut offset = range.start.to_offset(&snapshot);
10056                    let old_text = snapshot.text_for_range(range).collect::<String>();
10057
10058                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
10059                    let mut moved_since_edit = true;
10060                    for change in diff.iter_all_changes() {
10061                        let tag = change.tag();
10062                        let value = change.value();
10063                        match tag {
10064                            ChangeTag::Equal => {
10065                                offset += value.len();
10066                                moved_since_edit = true;
10067                            }
10068                            ChangeTag::Delete => {
10069                                let start = snapshot.anchor_after(offset);
10070                                let end = snapshot.anchor_before(offset + value.len());
10071                                if moved_since_edit {
10072                                    edits.push((start..end, String::new()));
10073                                } else {
10074                                    edits.last_mut().unwrap().0.end = end;
10075                                }
10076                                offset += value.len();
10077                                moved_since_edit = false;
10078                            }
10079                            ChangeTag::Insert => {
10080                                if moved_since_edit {
10081                                    let anchor = snapshot.anchor_after(offset);
10082                                    edits.push((anchor..anchor, value.to_string()));
10083                                } else {
10084                                    edits.last_mut().unwrap().1.push_str(value);
10085                                }
10086                                moved_since_edit = false;
10087                            }
10088                        }
10089                    }
10090                } else if range.end == range.start {
10091                    let anchor = snapshot.anchor_after(range.start);
10092                    edits.push((anchor..anchor, new_text));
10093                } else {
10094                    let edit_start = snapshot.anchor_after(range.start);
10095                    let edit_end = snapshot.anchor_before(range.end);
10096                    edits.push((edit_start..edit_end, new_text));
10097                }
10098            }
10099
10100            Ok(edits)
10101        })
10102    }
10103
10104    fn buffer_snapshot_for_lsp_version(
10105        &mut self,
10106        buffer: &Model<Buffer>,
10107        server_id: LanguageServerId,
10108        version: Option<i32>,
10109        cx: &AppContext,
10110    ) -> Result<TextBufferSnapshot> {
10111        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
10112
10113        if let Some(version) = version {
10114            let buffer_id = buffer.read(cx).remote_id();
10115            let snapshots = self
10116                .buffer_snapshots
10117                .get_mut(&buffer_id)
10118                .and_then(|m| m.get_mut(&server_id))
10119                .ok_or_else(|| {
10120                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
10121                })?;
10122
10123            let found_snapshot = snapshots
10124                .binary_search_by_key(&version, |e| e.version)
10125                .map(|ix| snapshots[ix].snapshot.clone())
10126                .map_err(|_| {
10127                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
10128                })?;
10129
10130            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
10131            Ok(found_snapshot)
10132        } else {
10133            Ok((buffer.read(cx)).text_snapshot())
10134        }
10135    }
10136
10137    pub fn language_servers(
10138        &self,
10139    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
10140        self.language_server_ids
10141            .iter()
10142            .map(|((worktree_id, server_name), server_id)| {
10143                (*server_id, server_name.clone(), *worktree_id)
10144            })
10145    }
10146
10147    pub fn supplementary_language_servers(
10148        &self,
10149    ) -> impl '_ + Iterator<Item = (&LanguageServerId, &LanguageServerName)> {
10150        self.supplementary_language_servers
10151            .iter()
10152            .map(|(id, (name, _))| (id, name))
10153    }
10154
10155    pub fn language_server_adapter_for_id(
10156        &self,
10157        id: LanguageServerId,
10158    ) -> Option<Arc<CachedLspAdapter>> {
10159        if let Some(LanguageServerState::Running { adapter, .. }) = self.language_servers.get(&id) {
10160            Some(adapter.clone())
10161        } else {
10162            None
10163        }
10164    }
10165
10166    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
10167        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
10168            Some(server.clone())
10169        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
10170            Some(Arc::clone(server))
10171        } else {
10172            None
10173        }
10174    }
10175
10176    pub fn language_servers_for_buffer(
10177        &self,
10178        buffer: &Buffer,
10179        cx: &AppContext,
10180    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10181        self.language_server_ids_for_buffer(buffer, cx)
10182            .into_iter()
10183            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
10184                LanguageServerState::Running {
10185                    adapter, server, ..
10186                } => Some((adapter, server)),
10187                _ => None,
10188            })
10189    }
10190
10191    fn primary_language_server_for_buffer(
10192        &self,
10193        buffer: &Buffer,
10194        cx: &AppContext,
10195    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10196        // The list of language servers is ordered based on the `language_servers` setting
10197        // for each language, thus we can consider the first one in the list to be the
10198        // primary one.
10199        self.language_servers_for_buffer(buffer, cx).next()
10200    }
10201
10202    pub fn language_server_for_buffer(
10203        &self,
10204        buffer: &Buffer,
10205        server_id: LanguageServerId,
10206        cx: &AppContext,
10207    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
10208        self.language_servers_for_buffer(buffer, cx)
10209            .find(|(_, s)| s.server_id() == server_id)
10210    }
10211
10212    fn language_server_ids_for_buffer(
10213        &self,
10214        buffer: &Buffer,
10215        cx: &AppContext,
10216    ) -> Vec<LanguageServerId> {
10217        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
10218            let worktree_id = file.worktree_id(cx);
10219            self.languages
10220                .lsp_adapters(&language)
10221                .iter()
10222                .flat_map(|adapter| {
10223                    let key = (worktree_id, adapter.name.clone());
10224                    self.language_server_ids.get(&key).copied()
10225                })
10226                .collect()
10227        } else {
10228            Vec::new()
10229        }
10230    }
10231
10232    pub fn task_context_for_location(
10233        &self,
10234        captured_variables: TaskVariables,
10235        location: Location,
10236        cx: &mut ModelContext<'_, Project>,
10237    ) -> Task<Option<TaskContext>> {
10238        if self.is_local_or_ssh() {
10239            let (worktree_id, cwd) = if let Some(worktree) = self.task_worktree(cx) {
10240                (
10241                    Some(worktree.read(cx).id()),
10242                    Some(self.task_cwd(worktree, cx)),
10243                )
10244            } else {
10245                (None, None)
10246            };
10247
10248            cx.spawn(|project, cx| async move {
10249                let mut task_variables = cx
10250                    .update(|cx| {
10251                        combine_task_variables(
10252                            captured_variables,
10253                            location,
10254                            BasicContextProvider::new(project.upgrade()?),
10255                            cx,
10256                        )
10257                        .log_err()
10258                    })
10259                    .ok()
10260                    .flatten()?;
10261                // Remove all custom entries starting with _, as they're not intended for use by the end user.
10262                task_variables.sweep();
10263
10264                let mut project_env = None;
10265                if let Some((worktree_id, cwd)) = worktree_id.zip(cwd.as_ref()) {
10266                    let env = Self::get_worktree_shell_env(project, worktree_id, cwd, cx).await;
10267                    if let Some(env) = env {
10268                        project_env.replace(env);
10269                    }
10270                };
10271
10272                Some(TaskContext {
10273                    project_env: project_env.unwrap_or_default(),
10274                    cwd,
10275                    task_variables,
10276                })
10277            })
10278        } else if let Some(project_id) = self
10279            .remote_id()
10280            .filter(|_| self.ssh_connection_string(cx).is_some())
10281        {
10282            let task_context = self.client().request(proto::TaskContextForLocation {
10283                project_id,
10284                location: Some(proto::Location {
10285                    buffer_id: location.buffer.read(cx).remote_id().into(),
10286                    start: Some(serialize_anchor(&location.range.start)),
10287                    end: Some(serialize_anchor(&location.range.end)),
10288                }),
10289            });
10290            cx.background_executor().spawn(async move {
10291                let task_context = task_context.await.log_err()?;
10292                Some(TaskContext {
10293                    project_env: task_context.project_env.into_iter().collect(),
10294                    cwd: task_context.cwd.map(PathBuf::from),
10295                    task_variables: task_context
10296                        .task_variables
10297                        .into_iter()
10298                        .filter_map(
10299                            |(variable_name, variable_value)| match variable_name.parse() {
10300                                Ok(variable_name) => Some((variable_name, variable_value)),
10301                                Err(()) => {
10302                                    log::error!("Unknown variable name: {variable_name}");
10303                                    None
10304                                }
10305                            },
10306                        )
10307                        .collect(),
10308                })
10309            })
10310        } else {
10311            Task::ready(None)
10312        }
10313    }
10314
10315    async fn get_worktree_shell_env(
10316        this: WeakModel<Self>,
10317        worktree_id: WorktreeId,
10318        cwd: &PathBuf,
10319        mut cx: AsyncAppContext,
10320    ) -> Option<HashMap<String, String>> {
10321        let cached_env = this
10322            .update(&mut cx, |project, _| {
10323                project.cached_shell_environments.get(&worktree_id).cloned()
10324            })
10325            .ok()?;
10326
10327        if let Some(env) = cached_env {
10328            Some(env)
10329        } else {
10330            let load_direnv = this
10331                .update(&mut cx, |_, cx| {
10332                    ProjectSettings::get_global(cx).load_direnv.clone()
10333                })
10334                .ok()?;
10335
10336            let shell_env = cx
10337                .background_executor()
10338                .spawn({
10339                    let cwd = cwd.clone();
10340                    async move {
10341                        load_shell_environment(&cwd, &load_direnv)
10342                            .await
10343                            .unwrap_or_default()
10344                    }
10345                })
10346                .await;
10347
10348            this.update(&mut cx, |project, _| {
10349                project
10350                    .cached_shell_environments
10351                    .insert(worktree_id, shell_env.clone());
10352            })
10353            .ok()?;
10354
10355            Some(shell_env)
10356        }
10357    }
10358
10359    pub fn task_templates(
10360        &self,
10361        worktree: Option<WorktreeId>,
10362        location: Option<Location>,
10363        cx: &mut ModelContext<Self>,
10364    ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
10365        if self.is_local_or_ssh() {
10366            let (file, language) = location
10367                .map(|location| {
10368                    let buffer = location.buffer.read(cx);
10369                    (
10370                        buffer.file().cloned(),
10371                        buffer.language_at(location.range.start),
10372                    )
10373                })
10374                .unwrap_or_default();
10375            Task::ready(Ok(self
10376                .task_inventory()
10377                .read(cx)
10378                .list_tasks(file, language, worktree, cx)))
10379        } else if let Some(project_id) = self
10380            .remote_id()
10381            .filter(|_| self.ssh_connection_string(cx).is_some())
10382        {
10383            let remote_templates =
10384                self.query_remote_task_templates(project_id, worktree, location.as_ref(), cx);
10385            cx.background_executor().spawn(remote_templates)
10386        } else {
10387            Task::ready(Ok(Vec::new()))
10388        }
10389    }
10390
10391    pub fn query_remote_task_templates(
10392        &self,
10393        project_id: u64,
10394        worktree: Option<WorktreeId>,
10395        location: Option<&Location>,
10396        cx: &AppContext,
10397    ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
10398        let client = self.client();
10399        let location = location.map(|location| serialize_location(location, cx));
10400        cx.spawn(|_| async move {
10401            let response = client
10402                .request(proto::TaskTemplates {
10403                    project_id,
10404                    worktree_id: worktree.map(|id| id.to_proto()),
10405                    location,
10406                })
10407                .await?;
10408
10409            Ok(response
10410                .templates
10411                .into_iter()
10412                .filter_map(|template_pair| {
10413                    let task_source_kind = match template_pair.kind?.kind? {
10414                        proto::task_source_kind::Kind::UserInput(_) => TaskSourceKind::UserInput,
10415                        proto::task_source_kind::Kind::Worktree(worktree) => {
10416                            TaskSourceKind::Worktree {
10417                                id: WorktreeId::from_proto(worktree.id),
10418                                abs_path: PathBuf::from(worktree.abs_path),
10419                                id_base: Cow::Owned(worktree.id_base),
10420                            }
10421                        }
10422                        proto::task_source_kind::Kind::AbsPath(abs_path) => {
10423                            TaskSourceKind::AbsPath {
10424                                id_base: Cow::Owned(abs_path.id_base),
10425                                abs_path: PathBuf::from(abs_path.abs_path),
10426                            }
10427                        }
10428                        proto::task_source_kind::Kind::Language(language) => {
10429                            TaskSourceKind::Language {
10430                                name: language.name.into(),
10431                            }
10432                        }
10433                    };
10434
10435                    let proto_template = template_pair.template?;
10436                    let reveal = match proto::RevealStrategy::from_i32(proto_template.reveal)
10437                        .unwrap_or(proto::RevealStrategy::RevealAlways)
10438                    {
10439                        proto::RevealStrategy::RevealAlways => RevealStrategy::Always,
10440                        proto::RevealStrategy::RevealNever => RevealStrategy::Never,
10441                    };
10442                    let hide = match proto::HideStrategy::from_i32(proto_template.hide)
10443                        .unwrap_or(proto::HideStrategy::HideNever)
10444                    {
10445                        proto::HideStrategy::HideAlways => HideStrategy::Always,
10446                        proto::HideStrategy::HideNever => HideStrategy::Never,
10447                        proto::HideStrategy::HideOnSuccess => HideStrategy::OnSuccess,
10448                    };
10449                    let shell = match proto_template
10450                        .shell
10451                        .and_then(|shell| shell.shell_type)
10452                        .unwrap_or(proto::shell::ShellType::System(proto::System {}))
10453                    {
10454                        proto::shell::ShellType::System(_) => Shell::System,
10455                        proto::shell::ShellType::Program(program) => Shell::Program(program),
10456                        proto::shell::ShellType::WithArguments(with_arguments) => {
10457                            Shell::WithArguments {
10458                                program: with_arguments.program,
10459                                args: with_arguments.args,
10460                            }
10461                        }
10462                    };
10463                    let task_template = TaskTemplate {
10464                        label: proto_template.label,
10465                        command: proto_template.command,
10466                        args: proto_template.args,
10467                        env: proto_template.env.into_iter().collect(),
10468                        cwd: proto_template.cwd,
10469                        use_new_terminal: proto_template.use_new_terminal,
10470                        allow_concurrent_runs: proto_template.allow_concurrent_runs,
10471                        reveal,
10472                        hide,
10473                        shell,
10474                        tags: proto_template.tags,
10475                    };
10476                    Some((task_source_kind, task_template))
10477                })
10478                .collect())
10479        })
10480    }
10481
10482    fn task_worktree(&self, cx: &AppContext) -> Option<Model<Worktree>> {
10483        let available_worktrees = self
10484            .worktrees(cx)
10485            .filter(|worktree| {
10486                let worktree = worktree.read(cx);
10487                worktree.is_visible()
10488                    && worktree.is_local()
10489                    && worktree.root_entry().map_or(false, |e| e.is_dir())
10490            })
10491            .collect::<Vec<_>>();
10492
10493        match available_worktrees.len() {
10494            0 => None,
10495            1 => Some(available_worktrees[0].clone()),
10496            _ => self.active_entry().and_then(|entry_id| {
10497                available_worktrees.into_iter().find_map(|worktree| {
10498                    if worktree.read(cx).contains_entry(entry_id) {
10499                        Some(worktree)
10500                    } else {
10501                        None
10502                    }
10503                })
10504            }),
10505        }
10506    }
10507
10508    fn task_cwd(&self, worktree: Model<Worktree>, cx: &AppContext) -> PathBuf {
10509        worktree.read(cx).abs_path().to_path_buf()
10510    }
10511}
10512
10513fn combine_task_variables(
10514    mut captured_variables: TaskVariables,
10515    location: Location,
10516    baseline: BasicContextProvider,
10517    cx: &mut AppContext,
10518) -> anyhow::Result<TaskVariables> {
10519    let language_context_provider = location
10520        .buffer
10521        .read(cx)
10522        .language()
10523        .and_then(|language| language.context_provider());
10524    let baseline = baseline
10525        .build_context(&captured_variables, &location, cx)
10526        .context("building basic default context")?;
10527    captured_variables.extend(baseline);
10528    if let Some(provider) = language_context_provider {
10529        captured_variables.extend(
10530            provider
10531                .build_context(&captured_variables, &location, cx)
10532                .context("building provider context")?,
10533        );
10534    }
10535    Ok(captured_variables)
10536}
10537
10538async fn populate_labels_for_symbols(
10539    symbols: Vec<CoreSymbol>,
10540    language_registry: &Arc<LanguageRegistry>,
10541    default_language: Option<Arc<Language>>,
10542    lsp_adapter: Option<Arc<CachedLspAdapter>>,
10543    output: &mut Vec<Symbol>,
10544) {
10545    #[allow(clippy::mutable_key_type)]
10546    let mut symbols_by_language = HashMap::<Option<Arc<Language>>, Vec<CoreSymbol>>::default();
10547
10548    let mut unknown_path = None;
10549    for symbol in symbols {
10550        let language = language_registry
10551            .language_for_file_path(&symbol.path.path)
10552            .await
10553            .ok()
10554            .or_else(|| {
10555                unknown_path.get_or_insert(symbol.path.path.clone());
10556                default_language.clone()
10557            });
10558        symbols_by_language
10559            .entry(language)
10560            .or_default()
10561            .push(symbol);
10562    }
10563
10564    if let Some(unknown_path) = unknown_path {
10565        log::info!(
10566            "no language found for symbol path {}",
10567            unknown_path.display()
10568        );
10569    }
10570
10571    let mut label_params = Vec::new();
10572    for (language, mut symbols) in symbols_by_language {
10573        label_params.clear();
10574        label_params.extend(
10575            symbols
10576                .iter_mut()
10577                .map(|symbol| (mem::take(&mut symbol.name), symbol.kind)),
10578        );
10579
10580        let mut labels = Vec::new();
10581        if let Some(language) = language {
10582            let lsp_adapter = lsp_adapter
10583                .clone()
10584                .or_else(|| language_registry.lsp_adapters(&language).first().cloned());
10585            if let Some(lsp_adapter) = lsp_adapter {
10586                labels = lsp_adapter
10587                    .labels_for_symbols(&label_params, &language)
10588                    .await
10589                    .log_err()
10590                    .unwrap_or_default();
10591            }
10592        }
10593
10594        for ((symbol, (name, _)), label) in symbols
10595            .into_iter()
10596            .zip(label_params.drain(..))
10597            .zip(labels.into_iter().chain(iter::repeat(None)))
10598        {
10599            output.push(Symbol {
10600                language_server_name: symbol.language_server_name,
10601                source_worktree_id: symbol.source_worktree_id,
10602                path: symbol.path,
10603                label: label.unwrap_or_else(|| CodeLabel::plain(name.clone(), None)),
10604                name,
10605                kind: symbol.kind,
10606                range: symbol.range,
10607                signature: symbol.signature,
10608            });
10609        }
10610    }
10611}
10612
10613async fn populate_labels_for_completions(
10614    mut new_completions: Vec<CoreCompletion>,
10615    language_registry: &Arc<LanguageRegistry>,
10616    language: Option<Arc<Language>>,
10617    lsp_adapter: Option<Arc<CachedLspAdapter>>,
10618    completions: &mut Vec<Completion>,
10619) {
10620    let lsp_completions = new_completions
10621        .iter_mut()
10622        .map(|completion| mem::take(&mut completion.lsp_completion))
10623        .collect::<Vec<_>>();
10624
10625    let labels = if let Some((language, lsp_adapter)) = language.as_ref().zip(lsp_adapter) {
10626        lsp_adapter
10627            .labels_for_completions(&lsp_completions, language)
10628            .await
10629            .log_err()
10630            .unwrap_or_default()
10631    } else {
10632        Vec::new()
10633    };
10634
10635    for ((completion, lsp_completion), label) in new_completions
10636        .into_iter()
10637        .zip(lsp_completions)
10638        .zip(labels.into_iter().chain(iter::repeat(None)))
10639    {
10640        let documentation = if let Some(docs) = &lsp_completion.documentation {
10641            Some(prepare_completion_documentation(docs, &language_registry, language.clone()).await)
10642        } else {
10643            None
10644        };
10645
10646        completions.push(Completion {
10647            old_range: completion.old_range,
10648            new_text: completion.new_text,
10649            label: label.unwrap_or_else(|| {
10650                CodeLabel::plain(
10651                    lsp_completion.label.clone(),
10652                    lsp_completion.filter_text.as_deref(),
10653                )
10654            }),
10655            server_id: completion.server_id,
10656            documentation,
10657            lsp_completion,
10658            confirm: None,
10659        })
10660    }
10661}
10662
10663fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
10664    code_actions
10665        .iter()
10666        .flat_map(|(kind, enabled)| {
10667            if *enabled {
10668                Some(kind.clone().into())
10669            } else {
10670                None
10671            }
10672        })
10673        .collect()
10674}
10675
10676fn glob_literal_prefix(glob: &str) -> &str {
10677    let mut literal_end = 0;
10678    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
10679        if part.contains(&['*', '?', '{', '}']) {
10680            break;
10681        } else {
10682            if i > 0 {
10683                // Account for separator prior to this part
10684                literal_end += path::MAIN_SEPARATOR.len_utf8();
10685            }
10686            literal_end += part.len();
10687        }
10688    }
10689    &glob[..literal_end]
10690}
10691
10692pub struct PathMatchCandidateSet {
10693    pub snapshot: Snapshot,
10694    pub include_ignored: bool,
10695    pub include_root_name: bool,
10696    pub candidates: Candidates,
10697}
10698
10699pub enum Candidates {
10700    /// Only consider directories.
10701    Directories,
10702    /// Only consider files.
10703    Files,
10704    /// Consider directories and files.
10705    Entries,
10706}
10707
10708impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
10709    type Candidates = PathMatchCandidateSetIter<'a>;
10710
10711    fn id(&self) -> usize {
10712        self.snapshot.id().to_usize()
10713    }
10714
10715    fn len(&self) -> usize {
10716        match self.candidates {
10717            Candidates::Files => {
10718                if self.include_ignored {
10719                    self.snapshot.file_count()
10720                } else {
10721                    self.snapshot.visible_file_count()
10722                }
10723            }
10724
10725            Candidates::Directories => {
10726                if self.include_ignored {
10727                    self.snapshot.dir_count()
10728                } else {
10729                    self.snapshot.visible_dir_count()
10730                }
10731            }
10732
10733            Candidates::Entries => {
10734                if self.include_ignored {
10735                    self.snapshot.entry_count()
10736                } else {
10737                    self.snapshot.visible_entry_count()
10738                }
10739            }
10740        }
10741    }
10742
10743    fn prefix(&self) -> Arc<str> {
10744        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
10745            self.snapshot.root_name().into()
10746        } else if self.include_root_name {
10747            format!("{}/", self.snapshot.root_name()).into()
10748        } else {
10749            Arc::default()
10750        }
10751    }
10752
10753    fn candidates(&'a self, start: usize) -> Self::Candidates {
10754        PathMatchCandidateSetIter {
10755            traversal: match self.candidates {
10756                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
10757                Candidates::Files => self.snapshot.files(self.include_ignored, start),
10758                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
10759            },
10760        }
10761    }
10762}
10763
10764pub struct PathMatchCandidateSetIter<'a> {
10765    traversal: Traversal<'a>,
10766}
10767
10768impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
10769    type Item = fuzzy::PathMatchCandidate<'a>;
10770
10771    fn next(&mut self) -> Option<Self::Item> {
10772        self.traversal
10773            .next()
10774            .map(|entry| fuzzy::PathMatchCandidate {
10775                is_dir: entry.kind.is_dir(),
10776                path: &entry.path,
10777                char_bag: entry.char_bag,
10778            })
10779    }
10780}
10781
10782impl EventEmitter<Event> for Project {}
10783
10784impl<'a> Into<SettingsLocation<'a>> for &'a ProjectPath {
10785    fn into(self) -> SettingsLocation<'a> {
10786        SettingsLocation {
10787            worktree_id: self.worktree_id.to_usize(),
10788            path: self.path.as_ref(),
10789        }
10790    }
10791}
10792
10793impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
10794    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
10795        Self {
10796            worktree_id,
10797            path: path.as_ref().into(),
10798        }
10799    }
10800}
10801
10802pub struct ProjectLspAdapterDelegate {
10803    project: WeakModel<Project>,
10804    worktree: worktree::Snapshot,
10805    fs: Arc<dyn Fs>,
10806    http_client: Arc<dyn HttpClient>,
10807    language_registry: Arc<LanguageRegistry>,
10808    shell_env: Mutex<Option<HashMap<String, String>>>,
10809    load_direnv: DirenvSettings,
10810}
10811
10812impl ProjectLspAdapterDelegate {
10813    pub fn new(
10814        project: &Project,
10815        worktree: &Model<Worktree>,
10816        cx: &ModelContext<Project>,
10817    ) -> Arc<Self> {
10818        let load_direnv = ProjectSettings::get_global(cx).load_direnv.clone();
10819        Arc::new(Self {
10820            project: cx.weak_model(),
10821            worktree: worktree.read(cx).snapshot(),
10822            fs: project.fs.clone(),
10823            http_client: project.client.http_client(),
10824            language_registry: project.languages.clone(),
10825            shell_env: Default::default(),
10826            load_direnv,
10827        })
10828    }
10829
10830    async fn load_shell_env(&self) {
10831        let worktree_abs_path = self.worktree.abs_path();
10832        let shell_env = load_shell_environment(&worktree_abs_path, &self.load_direnv)
10833            .await
10834            .with_context(|| {
10835                format!("failed to determine load login shell environment in {worktree_abs_path:?}")
10836            })
10837            .log_err()
10838            .unwrap_or_default();
10839        *self.shell_env.lock() = Some(shell_env);
10840    }
10841}
10842
10843#[async_trait]
10844impl LspAdapterDelegate for ProjectLspAdapterDelegate {
10845    fn show_notification(&self, message: &str, cx: &mut AppContext) {
10846        self.project
10847            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())))
10848            .ok();
10849    }
10850
10851    fn http_client(&self) -> Arc<dyn HttpClient> {
10852        self.http_client.clone()
10853    }
10854
10855    fn worktree_id(&self) -> u64 {
10856        self.worktree.id().to_proto()
10857    }
10858
10859    fn worktree_root_path(&self) -> &Path {
10860        self.worktree.abs_path().as_ref()
10861    }
10862
10863    async fn shell_env(&self) -> HashMap<String, String> {
10864        self.load_shell_env().await;
10865        self.shell_env.lock().as_ref().cloned().unwrap_or_default()
10866    }
10867
10868    #[cfg(not(target_os = "windows"))]
10869    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10870        let worktree_abs_path = self.worktree.abs_path();
10871        self.load_shell_env().await;
10872        let shell_path = self
10873            .shell_env
10874            .lock()
10875            .as_ref()
10876            .and_then(|shell_env| shell_env.get("PATH").cloned());
10877        which::which_in(command, shell_path.as_ref(), &worktree_abs_path).ok()
10878    }
10879
10880    #[cfg(target_os = "windows")]
10881    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
10882        // todo(windows) Getting the shell env variables in a current directory on Windows is more complicated than other platforms
10883        //               there isn't a 'default shell' necessarily. The closest would be the default profile on the windows terminal
10884        //               SEE: https://learn.microsoft.com/en-us/windows/terminal/customize-settings/startup
10885        which::which(command).ok()
10886    }
10887
10888    fn update_status(
10889        &self,
10890        server_name: LanguageServerName,
10891        status: language::LanguageServerBinaryStatus,
10892    ) {
10893        self.language_registry
10894            .update_lsp_status(server_name, status);
10895    }
10896
10897    async fn read_text_file(&self, path: PathBuf) -> Result<String> {
10898        if self.worktree.entry_for_path(&path).is_none() {
10899            return Err(anyhow!("no such path {path:?}"));
10900        }
10901        let path = self.worktree.absolutize(path.as_ref())?;
10902        let content = self.fs.load(&path).await?;
10903        Ok(content)
10904    }
10905}
10906
10907fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
10908    proto::Symbol {
10909        language_server_name: symbol.language_server_name.0.to_string(),
10910        source_worktree_id: symbol.source_worktree_id.to_proto(),
10911        worktree_id: symbol.path.worktree_id.to_proto(),
10912        path: symbol.path.path.to_string_lossy().to_string(),
10913        name: symbol.name.clone(),
10914        kind: unsafe { mem::transmute::<lsp::SymbolKind, i32>(symbol.kind) },
10915        start: Some(proto::PointUtf16 {
10916            row: symbol.range.start.0.row,
10917            column: symbol.range.start.0.column,
10918        }),
10919        end: Some(proto::PointUtf16 {
10920            row: symbol.range.end.0.row,
10921            column: symbol.range.end.0.column,
10922        }),
10923        signature: symbol.signature.to_vec(),
10924    }
10925}
10926
10927pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
10928    let mut path_components = path.components();
10929    let mut base_components = base.components();
10930    let mut components: Vec<Component> = Vec::new();
10931    loop {
10932        match (path_components.next(), base_components.next()) {
10933            (None, None) => break,
10934            (Some(a), None) => {
10935                components.push(a);
10936                components.extend(path_components.by_ref());
10937                break;
10938            }
10939            (None, _) => components.push(Component::ParentDir),
10940            (Some(a), Some(b)) if components.is_empty() && a == b => (),
10941            (Some(a), Some(Component::CurDir)) => components.push(a),
10942            (Some(a), Some(_)) => {
10943                components.push(Component::ParentDir);
10944                for _ in base_components {
10945                    components.push(Component::ParentDir);
10946                }
10947                components.push(a);
10948                components.extend(path_components.by_ref());
10949                break;
10950            }
10951        }
10952    }
10953    components.iter().map(|c| c.as_os_str()).collect()
10954}
10955
10956fn resolve_path(base: &Path, path: &Path) -> PathBuf {
10957    let mut result = base.to_path_buf();
10958    for component in path.components() {
10959        match component {
10960            Component::ParentDir => {
10961                result.pop();
10962            }
10963            Component::CurDir => (),
10964            _ => result.push(component),
10965        }
10966    }
10967    result
10968}
10969
10970/// ResolvedPath is a path that has been resolved to either a ProjectPath
10971/// or an AbsPath and that *exists*.
10972#[derive(Debug, Clone)]
10973pub enum ResolvedPath {
10974    ProjectPath(ProjectPath),
10975    AbsPath(PathBuf),
10976}
10977
10978impl Item for Buffer {
10979    fn try_open(
10980        project: &Model<Project>,
10981        path: &ProjectPath,
10982        cx: &mut AppContext,
10983    ) -> Option<Task<Result<Model<Self>>>> {
10984        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
10985    }
10986
10987    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
10988        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
10989    }
10990
10991    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
10992        File::from_dyn(self.file()).map(|file| ProjectPath {
10993            worktree_id: file.worktree_id(cx),
10994            path: file.path().clone(),
10995        })
10996    }
10997}
10998
10999impl Completion {
11000    /// A key that can be used to sort completions when displaying
11001    /// them to the user.
11002    pub fn sort_key(&self) -> (usize, &str) {
11003        let kind_key = match self.lsp_completion.kind {
11004            Some(lsp::CompletionItemKind::KEYWORD) => 0,
11005            Some(lsp::CompletionItemKind::VARIABLE) => 1,
11006            _ => 2,
11007        };
11008        (kind_key, &self.label.text[self.label.filter_range.clone()])
11009    }
11010
11011    /// Whether this completion is a snippet.
11012    pub fn is_snippet(&self) -> bool {
11013        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
11014    }
11015}
11016
11017fn include_text(server: &lsp::LanguageServer) -> Option<bool> {
11018    match server.capabilities().text_document_sync.as_ref()? {
11019        lsp::TextDocumentSyncCapability::Kind(kind) => match kind {
11020            &lsp::TextDocumentSyncKind::NONE => None,
11021            &lsp::TextDocumentSyncKind::FULL => Some(true),
11022            &lsp::TextDocumentSyncKind::INCREMENTAL => Some(false),
11023            _ => None,
11024        },
11025        lsp::TextDocumentSyncCapability::Options(options) => match options.save.as_ref()? {
11026            lsp::TextDocumentSyncSaveOptions::Supported(supported) => {
11027                if *supported {
11028                    Some(true)
11029                } else {
11030                    None
11031                }
11032            }
11033            lsp::TextDocumentSyncSaveOptions::SaveOptions(save_options) => {
11034                Some(save_options.include_text.unwrap_or(false))
11035            }
11036        },
11037    }
11038}
11039
11040async fn load_direnv_environment(dir: &Path) -> Result<Option<HashMap<String, String>>> {
11041    let Ok(direnv_path) = which::which("direnv") else {
11042        return Ok(None);
11043    };
11044
11045    let direnv_output = smol::process::Command::new(direnv_path)
11046        .args(["export", "json"])
11047        .current_dir(dir)
11048        .output()
11049        .await
11050        .context("failed to spawn direnv to get local environment variables")?;
11051
11052    anyhow::ensure!(
11053        direnv_output.status.success(),
11054        "direnv exited with error {:?}",
11055        direnv_output.status
11056    );
11057
11058    let output = String::from_utf8_lossy(&direnv_output.stdout);
11059    if output.is_empty() {
11060        return Ok(None);
11061    }
11062
11063    Ok(Some(
11064        serde_json::from_str(&output).context("failed to parse direnv output")?,
11065    ))
11066}
11067
11068async fn load_shell_environment(
11069    dir: &Path,
11070    load_direnv: &DirenvSettings,
11071) -> Result<HashMap<String, String>> {
11072    let direnv_environment = match load_direnv {
11073        DirenvSettings::ShellHook => None,
11074        DirenvSettings::Direct => load_direnv_environment(dir).await?,
11075    }
11076    .unwrap_or(HashMap::default());
11077
11078    let marker = "ZED_SHELL_START";
11079    let shell = env::var("SHELL").context(
11080        "SHELL environment variable is not assigned so we can't source login environment variables",
11081    )?;
11082
11083    // What we're doing here is to spawn a shell and then `cd` into
11084    // the project directory to get the env in there as if the user
11085    // `cd`'d into it. We do that because tools like direnv, asdf, ...
11086    // hook into `cd` and only set up the env after that.
11087    //
11088    // If the user selects `Direct` for direnv, it would set an environment
11089    // variable that later uses to know that it should not run the hook.
11090    // We would include in `.envs` call so it is okay to run the hook
11091    // even if direnv direct mode is enabled.
11092    //
11093    // In certain shells we need to execute additional_command in order to
11094    // trigger the behavior of direnv, etc.
11095    //
11096    //
11097    // The `exit 0` is the result of hours of debugging, trying to find out
11098    // why running this command here, without `exit 0`, would mess
11099    // up signal process for our process so that `ctrl-c` doesn't work
11100    // anymore.
11101    //
11102    // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'`  would
11103    // do that, but it does, and `exit 0` helps.
11104    let additional_command = PathBuf::from(&shell)
11105        .file_name()
11106        .and_then(|f| f.to_str())
11107        .and_then(|shell| match shell {
11108            "fish" => Some("emit fish_prompt;"),
11109            _ => None,
11110        });
11111
11112    let command = format!(
11113        "cd '{}';{} printf '%s' {marker}; /usr/bin/env; exit 0;",
11114        dir.display(),
11115        additional_command.unwrap_or("")
11116    );
11117
11118    let output = smol::process::Command::new(&shell)
11119        .args(["-i", "-c", &command])
11120        .envs(direnv_environment)
11121        .output()
11122        .await
11123        .context("failed to spawn login shell to source login environment variables")?;
11124
11125    anyhow::ensure!(
11126        output.status.success(),
11127        "login shell exited with error {:?}",
11128        output.status
11129    );
11130
11131    let stdout = String::from_utf8_lossy(&output.stdout);
11132    let env_output_start = stdout.find(marker).ok_or_else(|| {
11133        anyhow!(
11134            "failed to parse output of `env` command in login shell: {}",
11135            stdout
11136        )
11137    })?;
11138
11139    let mut parsed_env = HashMap::default();
11140    let env_output = &stdout[env_output_start + marker.len()..];
11141
11142    parse_env_output(env_output, |key, value| {
11143        parsed_env.insert(key, value);
11144    });
11145
11146    Ok(parsed_env)
11147}
11148
11149fn remove_empty_hover_blocks(mut hover: Hover) -> Option<Hover> {
11150    hover
11151        .contents
11152        .retain(|hover_block| !hover_block.text.trim().is_empty());
11153    if hover.contents.is_empty() {
11154        None
11155    } else {
11156        Some(hover)
11157    }
11158}
11159
11160#[derive(Debug)]
11161pub struct NoRepositoryError {}
11162
11163impl std::fmt::Display for NoRepositoryError {
11164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11165        write!(f, "no git repository for worktree found")
11166    }
11167}
11168
11169impl std::error::Error for NoRepositoryError {}
11170
11171fn serialize_location(location: &Location, cx: &AppContext) -> proto::Location {
11172    proto::Location {
11173        buffer_id: location.buffer.read(cx).remote_id().into(),
11174        start: Some(serialize_anchor(&location.range.start)),
11175        end: Some(serialize_anchor(&location.range.end)),
11176    }
11177}
11178
11179fn deserialize_location(
11180    project: &Model<Project>,
11181    location: proto::Location,
11182    cx: &mut AppContext,
11183) -> Task<Result<Location>> {
11184    let buffer_id = match BufferId::new(location.buffer_id) {
11185        Ok(id) => id,
11186        Err(e) => return Task::ready(Err(e)),
11187    };
11188    let buffer_task = project.update(cx, |project, cx| {
11189        project.wait_for_remote_buffer(buffer_id, cx)
11190    });
11191    cx.spawn(|_| async move {
11192        let buffer = buffer_task.await?;
11193        let start = location
11194            .start
11195            .and_then(deserialize_anchor)
11196            .context("missing task context location start")?;
11197        let end = location
11198            .end
11199            .and_then(deserialize_anchor)
11200            .context("missing task context location end")?;
11201        Ok(Location {
11202            buffer,
11203            range: start..end,
11204        })
11205    })
11206}
11207
11208#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
11209pub struct DiagnosticSummary {
11210    pub error_count: usize,
11211    pub warning_count: usize,
11212}
11213
11214impl DiagnosticSummary {
11215    pub fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
11216        let mut this = Self {
11217            error_count: 0,
11218            warning_count: 0,
11219        };
11220
11221        for entry in diagnostics {
11222            if entry.diagnostic.is_primary {
11223                match entry.diagnostic.severity {
11224                    DiagnosticSeverity::ERROR => this.error_count += 1,
11225                    DiagnosticSeverity::WARNING => this.warning_count += 1,
11226                    _ => {}
11227                }
11228            }
11229        }
11230
11231        this
11232    }
11233
11234    pub fn is_empty(&self) -> bool {
11235        self.error_count == 0 && self.warning_count == 0
11236    }
11237
11238    pub fn to_proto(
11239        &self,
11240        language_server_id: LanguageServerId,
11241        path: &Path,
11242    ) -> proto::DiagnosticSummary {
11243        proto::DiagnosticSummary {
11244            path: path.to_string_lossy().to_string(),
11245            language_server_id: language_server_id.0 as u64,
11246            error_count: self.error_count as u32,
11247            warning_count: self.warning_count as u32,
11248        }
11249    }
11250}
11251
11252pub fn sort_worktree_entries(entries: &mut Vec<Entry>) {
11253    entries.sort_by(|entry_a, entry_b| {
11254        compare_paths(
11255            (&entry_a.path, entry_a.is_file()),
11256            (&entry_b.path, entry_b.is_file()),
11257        )
11258    });
11259}