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