project.rs

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