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