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