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