project.rs

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