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