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