project.rs

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