project.rs

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