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