project.rs

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