project.rs

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