project.rs

   1pub mod agent_registry_store;
   2pub mod agent_server_store;
   3pub mod buffer_store;
   4pub mod color_extractor;
   5pub mod connection_manager;
   6pub mod context_server_store;
   7pub mod debounced_delay;
   8pub mod debugger;
   9pub mod git_store;
  10pub mod image_store;
  11pub mod lsp_command;
  12pub mod lsp_store;
  13pub mod manifest_tree;
  14pub mod prettier_store;
  15pub mod project_search;
  16pub mod project_settings;
  17pub mod search;
  18pub mod task_inventory;
  19pub mod task_store;
  20pub mod telemetry_snapshot;
  21pub mod terminals;
  22pub mod toolchain_store;
  23pub mod trusted_worktrees;
  24pub mod worktree_store;
  25
  26mod environment;
  27use buffer_diff::BufferDiff;
  28use context_server_store::ContextServerStore;
  29pub use environment::ProjectEnvironmentEvent;
  30use git::repository::get_git_committer;
  31use git_store::{Repository, RepositoryId};
  32pub mod search_history;
  33pub mod yarn;
  34
  35use dap::inline_value::{InlineValueLocation, VariableLookupKind, VariableScope};
  36use itertools::Either;
  37
  38use crate::{
  39    git_store::GitStore,
  40    lsp_store::{SymbolLocation, log_store::LogKind},
  41    project_search::SearchResultsHandle,
  42    trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
  43    worktree_store::WorktreeIdCounter,
  44};
  45pub use agent_registry_store::{AgentRegistryStore, RegistryAgent};
  46pub use agent_server_store::{
  47    AgentServerStore, AgentServersUpdated, ExternalAgentServerName, ExternalAgentSource,
  48};
  49pub use git_store::{
  50    ConflictRegion, ConflictSet, ConflictSetSnapshot, ConflictSetUpdate,
  51    git_traversal::{ChildEntriesGitIter, GitEntry, GitEntryRef, GitTraversal},
  52};
  53pub use manifest_tree::ManifestTree;
  54pub use project_search::{Search, SearchResults};
  55
  56use anyhow::{Context as _, Result, anyhow};
  57use buffer_store::{BufferStore, BufferStoreEvent};
  58use client::{
  59    Client, Collaborator, PendingEntitySubscription, ProjectId, TypedEnvelope, UserStore, proto,
  60};
  61use clock::ReplicaId;
  62
  63use dap::client::DebugAdapterClient;
  64
  65use collections::{BTreeSet, HashMap, HashSet, IndexSet};
  66use debounced_delay::DebouncedDelay;
  67pub use debugger::breakpoint_store::BreakpointWithPosition;
  68use debugger::{
  69    breakpoint_store::{ActiveStackFrame, BreakpointStore},
  70    dap_store::{DapStore, DapStoreEvent},
  71    session::Session,
  72};
  73
  74pub use environment::ProjectEnvironment;
  75
  76use futures::{
  77    StreamExt,
  78    channel::mpsc::{self, UnboundedReceiver},
  79    future::try_join_all,
  80};
  81pub use image_store::{ImageItem, ImageStore};
  82use image_store::{ImageItemEvent, ImageStoreEvent};
  83
  84use ::git::{blame::Blame, status::FileStatus};
  85use gpui::{
  86    App, AppContext, AsyncApp, BorrowAppContext, Context, Entity, EventEmitter, Hsla, SharedString,
  87    Task, WeakEntity, Window,
  88};
  89use language::{
  90    Buffer, BufferEvent, Capability, CodeLabel, CursorShape, DiskState, Language, LanguageName,
  91    LanguageRegistry, PointUtf16, ToOffset, ToPointUtf16, Toolchain, ToolchainMetadata,
  92    ToolchainScope, Transaction, Unclipped, language_settings::InlayHintKind,
  93    proto::split_operations,
  94};
  95use lsp::{
  96    CodeActionKind, CompletionContext, CompletionItemKind, DocumentHighlightKind, InsertTextMode,
  97    LanguageServerBinary, LanguageServerId, LanguageServerName, LanguageServerSelector,
  98    MessageActionItem,
  99};
 100use lsp_command::*;
 101use lsp_store::{CompletionDocumentation, LspFormatTarget, OpenLspBufferHandle};
 102pub use manifest_tree::ManifestProvidersStore;
 103use node_runtime::NodeRuntime;
 104use parking_lot::Mutex;
 105pub use prettier_store::PrettierStore;
 106use project_settings::{ProjectSettings, SettingsObserver, SettingsObserverEvent};
 107#[cfg(target_os = "windows")]
 108use remote::wsl_path_to_windows_path;
 109use remote::{RemoteClient, RemoteConnectionOptions};
 110use rpc::{
 111    AnyProtoClient, ErrorCode,
 112    proto::{LanguageServerPromptResponse, REMOTE_SERVER_PROJECT_ID},
 113};
 114use search::{SearchInputKind, SearchQuery, SearchResult};
 115use search_history::SearchHistory;
 116use settings::{InvalidSettingsError, RegisterSetting, Settings, SettingsLocation, SettingsStore};
 117use snippet::Snippet;
 118pub use snippet_provider;
 119use snippet_provider::SnippetProvider;
 120use std::{
 121    borrow::Cow,
 122    collections::BTreeMap,
 123    ffi::OsString,
 124    ops::{Not as _, Range},
 125    path::{Path, PathBuf},
 126    pin::pin,
 127    str::{self, FromStr},
 128    sync::Arc,
 129    time::Duration,
 130};
 131
 132use task_store::TaskStore;
 133use terminals::Terminals;
 134use text::{Anchor, BufferId, OffsetRangeExt, Point, Rope};
 135use toolchain_store::EmptyToolchainStore;
 136use util::{
 137    ResultExt as _, maybe,
 138    paths::{PathStyle, SanitizedPath, is_absolute},
 139    rel_path::RelPath,
 140};
 141use worktree::{CreatedEntry, Snapshot, Traversal};
 142pub use worktree::{
 143    Entry, EntryKind, FS_WATCH_LATENCY, File, LocalWorktree, PathChange, ProjectEntryId,
 144    UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
 145};
 146use worktree_store::{WorktreeStore, WorktreeStoreEvent};
 147
 148pub use fs::*;
 149pub use language::Location;
 150#[cfg(any(test, feature = "test-support"))]
 151pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
 152pub use task_inventory::{
 153    BasicContextProvider, ContextProviderWithTasks, DebugScenarioContext, Inventory, TaskContexts,
 154    TaskSourceKind,
 155};
 156
 157pub use buffer_store::ProjectTransaction;
 158pub use lsp_store::{
 159    DiagnosticSummary, InvalidationStrategy, LanguageServerLogType, LanguageServerProgress,
 160    LanguageServerPromptRequest, LanguageServerStatus, LanguageServerToQuery, LspStore,
 161    LspStoreEvent, ProgressToken, SERVER_PROGRESS_THROTTLE_TIMEOUT,
 162};
 163pub use toolchain_store::{ToolchainStore, Toolchains};
 164const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
 165
 166#[derive(Clone, Copy, Debug)]
 167pub struct LocalProjectFlags {
 168    pub init_worktree_trust: bool,
 169    pub watch_global_configs: bool,
 170}
 171
 172impl Default for LocalProjectFlags {
 173    fn default() -> Self {
 174        Self {
 175            init_worktree_trust: true,
 176            watch_global_configs: true,
 177        }
 178    }
 179}
 180
 181pub trait ProjectItem: 'static {
 182    fn try_open(
 183        project: &Entity<Project>,
 184        path: &ProjectPath,
 185        cx: &mut App,
 186    ) -> Option<Task<Result<Entity<Self>>>>
 187    where
 188        Self: Sized;
 189    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId>;
 190    fn project_path(&self, cx: &App) -> Option<ProjectPath>;
 191    fn is_dirty(&self) -> bool;
 192}
 193
 194#[derive(Clone)]
 195pub enum OpenedBufferEvent {
 196    Disconnected,
 197    Ok(BufferId),
 198    Err(BufferId, Arc<anyhow::Error>),
 199}
 200
 201/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
 202/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
 203/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
 204///
 205/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
 206pub struct Project {
 207    active_entry: Option<ProjectEntryId>,
 208    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
 209    languages: Arc<LanguageRegistry>,
 210    dap_store: Entity<DapStore>,
 211    agent_server_store: Entity<AgentServerStore>,
 212
 213    breakpoint_store: Entity<BreakpointStore>,
 214    collab_client: Arc<client::Client>,
 215    join_project_response_message_id: u32,
 216    task_store: Entity<TaskStore>,
 217    user_store: Entity<UserStore>,
 218    fs: Arc<dyn Fs>,
 219    remote_client: Option<Entity<RemoteClient>>,
 220    // todo lw explain the client_state x remote_client matrix, its super confusing
 221    client_state: ProjectClientState,
 222    git_store: Entity<GitStore>,
 223    collaborators: HashMap<proto::PeerId, Collaborator>,
 224    client_subscriptions: Vec<client::Subscription>,
 225    worktree_store: Entity<WorktreeStore>,
 226    buffer_store: Entity<BufferStore>,
 227    context_server_store: Entity<ContextServerStore>,
 228    image_store: Entity<ImageStore>,
 229    lsp_store: Entity<LspStore>,
 230    _subscriptions: Vec<gpui::Subscription>,
 231    buffers_needing_diff: HashSet<WeakEntity<Buffer>>,
 232    git_diff_debouncer: DebouncedDelay<Self>,
 233    remotely_created_models: Arc<Mutex<RemotelyCreatedModels>>,
 234    terminals: Terminals,
 235    node: Option<NodeRuntime>,
 236    search_history: SearchHistory,
 237    search_included_history: SearchHistory,
 238    search_excluded_history: SearchHistory,
 239    snippets: Entity<SnippetProvider>,
 240    environment: Entity<ProjectEnvironment>,
 241    settings_observer: Entity<SettingsObserver>,
 242    toolchain_store: Option<Entity<ToolchainStore>>,
 243    agent_location: Option<AgentLocation>,
 244    downloading_files: Arc<Mutex<HashMap<(WorktreeId, String), DownloadingFile>>>,
 245}
 246
 247struct DownloadingFile {
 248    destination_path: PathBuf,
 249    chunks: Vec<u8>,
 250    total_size: u64,
 251    file_id: Option<u64>, // Set when we receive the State message
 252}
 253
 254#[derive(Clone, Debug, PartialEq, Eq)]
 255pub struct AgentLocation {
 256    pub buffer: WeakEntity<Buffer>,
 257    pub position: Anchor,
 258}
 259
 260#[derive(Default)]
 261struct RemotelyCreatedModels {
 262    worktrees: Vec<Entity<Worktree>>,
 263    buffers: Vec<Entity<Buffer>>,
 264    retain_count: usize,
 265}
 266
 267struct RemotelyCreatedModelGuard {
 268    remote_models: std::sync::Weak<Mutex<RemotelyCreatedModels>>,
 269}
 270
 271impl Drop for RemotelyCreatedModelGuard {
 272    fn drop(&mut self) {
 273        if let Some(remote_models) = self.remote_models.upgrade() {
 274            let mut remote_models = remote_models.lock();
 275            assert!(
 276                remote_models.retain_count > 0,
 277                "RemotelyCreatedModelGuard dropped too many times"
 278            );
 279            remote_models.retain_count -= 1;
 280            if remote_models.retain_count == 0 {
 281                remote_models.buffers.clear();
 282                remote_models.worktrees.clear();
 283            }
 284        }
 285    }
 286}
 287/// Message ordered with respect to buffer operations
 288#[derive(Debug)]
 289enum BufferOrderedMessage {
 290    Operation {
 291        buffer_id: BufferId,
 292        operation: proto::Operation,
 293    },
 294    LanguageServerUpdate {
 295        language_server_id: LanguageServerId,
 296        message: proto::update_language_server::Variant,
 297        name: Option<LanguageServerName>,
 298    },
 299    Resync,
 300}
 301
 302#[derive(Debug)]
 303enum ProjectClientState {
 304    /// Single-player mode.
 305    Local,
 306    /// Multi-player mode but still a local project.
 307    Shared { remote_id: u64 },
 308    /// Multi-player mode but working on a remote project.
 309    Remote {
 310        sharing_has_stopped: bool,
 311        capability: Capability,
 312        remote_id: u64,
 313        replica_id: ReplicaId,
 314    },
 315}
 316
 317/// A link to display in a toast notification, useful to point to documentation.
 318#[derive(PartialEq, Debug, Clone)]
 319pub struct ToastLink {
 320    pub label: &'static str,
 321    pub url: &'static str,
 322}
 323
 324#[derive(Clone, Debug, PartialEq)]
 325pub enum Event {
 326    LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
 327    LanguageServerRemoved(LanguageServerId),
 328    LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
 329    // [`lsp::notification::DidOpenTextDocument`] was sent to this server using the buffer data.
 330    // Zed's buffer-related data is updated accordingly.
 331    LanguageServerBufferRegistered {
 332        server_id: LanguageServerId,
 333        buffer_id: BufferId,
 334        buffer_abs_path: PathBuf,
 335        name: Option<LanguageServerName>,
 336    },
 337    ToggleLspLogs {
 338        server_id: LanguageServerId,
 339        enabled: bool,
 340        toggled_log_kind: LogKind,
 341    },
 342    Toast {
 343        notification_id: SharedString,
 344        message: String,
 345        /// Optional link to display as a button in the toast.
 346        link: Option<ToastLink>,
 347    },
 348    HideToast {
 349        notification_id: SharedString,
 350    },
 351    LanguageServerPrompt(LanguageServerPromptRequest),
 352    LanguageNotFound(Entity<Buffer>),
 353    ActiveEntryChanged(Option<ProjectEntryId>),
 354    ActivateProjectPanel,
 355    WorktreeAdded(WorktreeId),
 356    WorktreeOrderChanged,
 357    WorktreeRemoved(WorktreeId),
 358    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
 359    DiskBasedDiagnosticsStarted {
 360        language_server_id: LanguageServerId,
 361    },
 362    DiskBasedDiagnosticsFinished {
 363        language_server_id: LanguageServerId,
 364    },
 365    DiagnosticsUpdated {
 366        paths: Vec<ProjectPath>,
 367        language_server_id: LanguageServerId,
 368    },
 369    RemoteIdChanged(Option<u64>),
 370    DisconnectedFromHost,
 371    DisconnectedFromRemote {
 372        server_not_running: bool,
 373    },
 374    Closed,
 375    DeletedEntry(WorktreeId, ProjectEntryId),
 376    CollaboratorUpdated {
 377        old_peer_id: proto::PeerId,
 378        new_peer_id: proto::PeerId,
 379    },
 380    CollaboratorJoined(proto::PeerId),
 381    CollaboratorLeft(proto::PeerId),
 382    HostReshared,
 383    Reshared,
 384    Rejoined,
 385    RefreshInlayHints {
 386        server_id: LanguageServerId,
 387        request_id: Option<usize>,
 388    },
 389    RefreshSemanticTokens {
 390        server_id: LanguageServerId,
 391        request_id: Option<usize>,
 392    },
 393    RefreshCodeLens,
 394    RevealInProjectPanel(ProjectEntryId),
 395    SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
 396    ExpandedAllForEntry(WorktreeId, ProjectEntryId),
 397    EntryRenamed(ProjectTransaction, ProjectPath, PathBuf),
 398    WorkspaceEditApplied(ProjectTransaction),
 399    AgentLocationChanged,
 400    BufferEdited,
 401}
 402
 403pub struct AgentLocationChanged;
 404
 405pub enum DebugAdapterClientState {
 406    Starting(Task<Option<Arc<DebugAdapterClient>>>),
 407    Running(Arc<DebugAdapterClient>),
 408}
 409
 410#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 411pub struct ProjectPath {
 412    pub worktree_id: WorktreeId,
 413    pub path: Arc<RelPath>,
 414}
 415
 416impl ProjectPath {
 417    pub fn from_file(value: &dyn language::File, cx: &App) -> Self {
 418        ProjectPath {
 419            worktree_id: value.worktree_id(cx),
 420            path: value.path().clone(),
 421        }
 422    }
 423
 424    pub fn from_proto(p: proto::ProjectPath) -> Option<Self> {
 425        Some(Self {
 426            worktree_id: WorktreeId::from_proto(p.worktree_id),
 427            path: RelPath::from_proto(&p.path).log_err()?,
 428        })
 429    }
 430
 431    pub fn to_proto(&self) -> proto::ProjectPath {
 432        proto::ProjectPath {
 433            worktree_id: self.worktree_id.to_proto(),
 434            path: self.path.as_ref().to_proto(),
 435        }
 436    }
 437
 438    pub fn root_path(worktree_id: WorktreeId) -> Self {
 439        Self {
 440            worktree_id,
 441            path: RelPath::empty().into(),
 442        }
 443    }
 444
 445    pub fn starts_with(&self, other: &ProjectPath) -> bool {
 446        self.worktree_id == other.worktree_id && self.path.starts_with(&other.path)
 447    }
 448}
 449
 450#[derive(Debug, Default)]
 451pub enum PrepareRenameResponse {
 452    Success(Range<Anchor>),
 453    OnlyUnpreparedRenameSupported,
 454    #[default]
 455    InvalidPosition,
 456}
 457
 458#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
 459pub enum InlayId {
 460    EditPrediction(usize),
 461    DebuggerValue(usize),
 462    // LSP
 463    Hint(usize),
 464    Color(usize),
 465    ReplResult(usize),
 466}
 467
 468impl InlayId {
 469    pub fn id(&self) -> usize {
 470        match self {
 471            Self::EditPrediction(id) => *id,
 472            Self::DebuggerValue(id) => *id,
 473            Self::Hint(id) => *id,
 474            Self::Color(id) => *id,
 475            Self::ReplResult(id) => *id,
 476        }
 477    }
 478}
 479
 480#[derive(Debug, Clone, PartialEq, Eq)]
 481pub struct InlayHint {
 482    pub position: language::Anchor,
 483    pub label: InlayHintLabel,
 484    pub kind: Option<InlayHintKind>,
 485    pub padding_left: bool,
 486    pub padding_right: bool,
 487    pub tooltip: Option<InlayHintTooltip>,
 488    pub resolve_state: ResolveState,
 489}
 490
 491/// The user's intent behind a given completion confirmation.
 492#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
 493pub enum CompletionIntent {
 494    /// The user intends to 'commit' this result, if possible.
 495    /// Completion confirmations should run side effects.
 496    ///
 497    /// For LSP completions, will respect the setting `completions.lsp_insert_mode`.
 498    Complete,
 499    /// Similar to [Self::Complete], but behaves like `lsp_insert_mode` is set to `insert`.
 500    CompleteWithInsert,
 501    /// Similar to [Self::Complete], but behaves like `lsp_insert_mode` is set to `replace`.
 502    CompleteWithReplace,
 503    /// The user intends to continue 'composing' this completion.
 504    /// Completion confirmations should not run side effects and
 505    /// let the user continue composing their action.
 506    Compose,
 507}
 508
 509impl CompletionIntent {
 510    pub fn is_complete(&self) -> bool {
 511        self == &Self::Complete
 512    }
 513
 514    pub fn is_compose(&self) -> bool {
 515        self == &Self::Compose
 516    }
 517}
 518
 519/// Similar to `CoreCompletion`, but with extra metadata attached.
 520#[derive(Clone)]
 521pub struct Completion {
 522    /// The range of text that will be replaced by this completion.
 523    pub replace_range: Range<Anchor>,
 524    /// The new text that will be inserted.
 525    pub new_text: String,
 526    /// A label for this completion that is shown in the menu.
 527    pub label: CodeLabel,
 528    /// The documentation for this completion.
 529    pub documentation: Option<CompletionDocumentation>,
 530    /// Completion data source which it was constructed from.
 531    pub source: CompletionSource,
 532    /// A path to an icon for this completion that is shown in the menu.
 533    pub icon_path: Option<SharedString>,
 534    /// Text starting here and ending at the cursor will be used as the query for filtering this completion.
 535    ///
 536    /// If None, the start of the surrounding word is used.
 537    pub match_start: Option<text::Anchor>,
 538    /// Key used for de-duplicating snippets. If None, always considered unique.
 539    pub snippet_deduplication_key: Option<(usize, usize)>,
 540    /// Whether to adjust indentation (the default) or not.
 541    pub insert_text_mode: Option<InsertTextMode>,
 542    /// An optional callback to invoke when this completion is confirmed.
 543    /// Returns whether new completions should be retriggered after the current one.
 544    /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
 545    /// if no confirmation is provided or `false` is returned, the completion will be committed.
 546    pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut Window, &mut App) -> bool>>,
 547}
 548
 549#[derive(Debug, Clone)]
 550pub enum CompletionSource {
 551    Lsp {
 552        /// The alternate `insert` range, if provided by the LSP server.
 553        insert_range: Option<Range<Anchor>>,
 554        /// The id of the language server that produced this completion.
 555        server_id: LanguageServerId,
 556        /// The raw completion provided by the language server.
 557        lsp_completion: Box<lsp::CompletionItem>,
 558        /// A set of defaults for this completion item.
 559        lsp_defaults: Option<Arc<lsp::CompletionListItemDefaults>>,
 560        /// Whether this completion has been resolved, to ensure it happens once per completion.
 561        resolved: bool,
 562    },
 563    Dap {
 564        /// The sort text for this completion.
 565        sort_text: String,
 566    },
 567    Custom,
 568    BufferWord {
 569        word_range: Range<Anchor>,
 570        resolved: bool,
 571    },
 572}
 573
 574impl CompletionSource {
 575    pub fn server_id(&self) -> Option<LanguageServerId> {
 576        if let CompletionSource::Lsp { server_id, .. } = self {
 577            Some(*server_id)
 578        } else {
 579            None
 580        }
 581    }
 582
 583    pub fn lsp_completion(&self, apply_defaults: bool) -> Option<Cow<'_, lsp::CompletionItem>> {
 584        if let Self::Lsp {
 585            lsp_completion,
 586            lsp_defaults,
 587            ..
 588        } = self
 589        {
 590            if apply_defaults && let Some(lsp_defaults) = lsp_defaults {
 591                let mut completion_with_defaults = *lsp_completion.clone();
 592                let default_commit_characters = lsp_defaults.commit_characters.as_ref();
 593                let default_edit_range = lsp_defaults.edit_range.as_ref();
 594                let default_insert_text_format = lsp_defaults.insert_text_format.as_ref();
 595                let default_insert_text_mode = lsp_defaults.insert_text_mode.as_ref();
 596
 597                if default_commit_characters.is_some()
 598                    || default_edit_range.is_some()
 599                    || default_insert_text_format.is_some()
 600                    || default_insert_text_mode.is_some()
 601                {
 602                    if completion_with_defaults.commit_characters.is_none()
 603                        && default_commit_characters.is_some()
 604                    {
 605                        completion_with_defaults.commit_characters =
 606                            default_commit_characters.cloned()
 607                    }
 608                    if completion_with_defaults.text_edit.is_none() {
 609                        match default_edit_range {
 610                            Some(lsp::CompletionListItemDefaultsEditRange::Range(range)) => {
 611                                completion_with_defaults.text_edit =
 612                                    Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
 613                                        range: *range,
 614                                        new_text: completion_with_defaults.label.clone(),
 615                                    }))
 616                            }
 617                            Some(lsp::CompletionListItemDefaultsEditRange::InsertAndReplace {
 618                                insert,
 619                                replace,
 620                            }) => {
 621                                completion_with_defaults.text_edit =
 622                                    Some(lsp::CompletionTextEdit::InsertAndReplace(
 623                                        lsp::InsertReplaceEdit {
 624                                            new_text: completion_with_defaults.label.clone(),
 625                                            insert: *insert,
 626                                            replace: *replace,
 627                                        },
 628                                    ))
 629                            }
 630                            None => {}
 631                        }
 632                    }
 633                    if completion_with_defaults.insert_text_format.is_none()
 634                        && default_insert_text_format.is_some()
 635                    {
 636                        completion_with_defaults.insert_text_format =
 637                            default_insert_text_format.cloned()
 638                    }
 639                    if completion_with_defaults.insert_text_mode.is_none()
 640                        && default_insert_text_mode.is_some()
 641                    {
 642                        completion_with_defaults.insert_text_mode =
 643                            default_insert_text_mode.cloned()
 644                    }
 645                }
 646                return Some(Cow::Owned(completion_with_defaults));
 647            }
 648            Some(Cow::Borrowed(lsp_completion))
 649        } else {
 650            None
 651        }
 652    }
 653}
 654
 655impl std::fmt::Debug for Completion {
 656    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 657        f.debug_struct("Completion")
 658            .field("replace_range", &self.replace_range)
 659            .field("new_text", &self.new_text)
 660            .field("label", &self.label)
 661            .field("documentation", &self.documentation)
 662            .field("source", &self.source)
 663            .finish()
 664    }
 665}
 666
 667/// Response from a source of completions.
 668pub struct CompletionResponse {
 669    pub completions: Vec<Completion>,
 670    pub display_options: CompletionDisplayOptions,
 671    /// When false, indicates that the list is complete and does not need to be re-queried if it
 672    /// can be filtered instead.
 673    pub is_incomplete: bool,
 674}
 675
 676#[derive(Default)]
 677pub struct CompletionDisplayOptions {
 678    pub dynamic_width: bool,
 679}
 680
 681impl CompletionDisplayOptions {
 682    pub fn merge(&mut self, other: &CompletionDisplayOptions) {
 683        self.dynamic_width = self.dynamic_width && other.dynamic_width;
 684    }
 685}
 686
 687/// Response from language server completion request.
 688#[derive(Clone, Debug, Default)]
 689pub(crate) struct CoreCompletionResponse {
 690    pub completions: Vec<CoreCompletion>,
 691    /// When false, indicates that the list is complete and does not need to be re-queried if it
 692    /// can be filtered instead.
 693    pub is_incomplete: bool,
 694}
 695
 696/// A generic completion that can come from different sources.
 697#[derive(Clone, Debug)]
 698pub(crate) struct CoreCompletion {
 699    replace_range: Range<Anchor>,
 700    new_text: String,
 701    source: CompletionSource,
 702}
 703
 704/// A code action provided by a language server.
 705#[derive(Clone, Debug, PartialEq)]
 706pub struct CodeAction {
 707    /// The id of the language server that produced this code action.
 708    pub server_id: LanguageServerId,
 709    /// The range of the buffer where this code action is applicable.
 710    pub range: Range<Anchor>,
 711    /// The raw code action provided by the language server.
 712    /// Can be either an action or a command.
 713    pub lsp_action: LspAction,
 714    /// Whether the action needs to be resolved using the language server.
 715    pub resolved: bool,
 716}
 717
 718/// An action sent back by a language server.
 719#[derive(Clone, Debug, PartialEq)]
 720pub enum LspAction {
 721    /// An action with the full data, may have a command or may not.
 722    /// May require resolving.
 723    Action(Box<lsp::CodeAction>),
 724    /// A command data to run as an action.
 725    Command(lsp::Command),
 726    /// A code lens data to run as an action.
 727    CodeLens(lsp::CodeLens),
 728}
 729
 730impl LspAction {
 731    pub fn title(&self) -> &str {
 732        match self {
 733            Self::Action(action) => &action.title,
 734            Self::Command(command) => &command.title,
 735            Self::CodeLens(lens) => lens
 736                .command
 737                .as_ref()
 738                .map(|command| command.title.as_str())
 739                .unwrap_or("Unknown command"),
 740        }
 741    }
 742
 743    pub fn action_kind(&self) -> Option<lsp::CodeActionKind> {
 744        match self {
 745            Self::Action(action) => action.kind.clone(),
 746            Self::Command(_) => Some(lsp::CodeActionKind::new("command")),
 747            Self::CodeLens(_) => Some(lsp::CodeActionKind::new("code lens")),
 748        }
 749    }
 750
 751    fn edit(&self) -> Option<&lsp::WorkspaceEdit> {
 752        match self {
 753            Self::Action(action) => action.edit.as_ref(),
 754            Self::Command(_) => None,
 755            Self::CodeLens(_) => None,
 756        }
 757    }
 758
 759    fn command(&self) -> Option<&lsp::Command> {
 760        match self {
 761            Self::Action(action) => action.command.as_ref(),
 762            Self::Command(command) => Some(command),
 763            Self::CodeLens(lens) => lens.command.as_ref(),
 764        }
 765    }
 766}
 767
 768#[derive(Debug, Clone, PartialEq, Eq)]
 769pub enum ResolveState {
 770    Resolved,
 771    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
 772    Resolving,
 773}
 774impl InlayHint {
 775    pub fn text(&self) -> Rope {
 776        match &self.label {
 777            InlayHintLabel::String(s) => Rope::from(s),
 778            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &*part.value).collect(),
 779        }
 780    }
 781}
 782
 783#[derive(Debug, Clone, PartialEq, Eq)]
 784pub enum InlayHintLabel {
 785    String(String),
 786    LabelParts(Vec<InlayHintLabelPart>),
 787}
 788
 789#[derive(Debug, Clone, PartialEq, Eq)]
 790pub struct InlayHintLabelPart {
 791    pub value: String,
 792    pub tooltip: Option<InlayHintLabelPartTooltip>,
 793    pub location: Option<(LanguageServerId, lsp::Location)>,
 794}
 795
 796#[derive(Debug, Clone, PartialEq, Eq)]
 797pub enum InlayHintTooltip {
 798    String(String),
 799    MarkupContent(MarkupContent),
 800}
 801
 802#[derive(Debug, Clone, PartialEq, Eq)]
 803pub enum InlayHintLabelPartTooltip {
 804    String(String),
 805    MarkupContent(MarkupContent),
 806}
 807
 808#[derive(Debug, Clone, PartialEq, Eq)]
 809pub struct MarkupContent {
 810    pub kind: HoverBlockKind,
 811    pub value: String,
 812}
 813
 814#[derive(Debug, Clone, PartialEq)]
 815pub struct LocationLink {
 816    pub origin: Option<Location>,
 817    pub target: Location,
 818}
 819
 820#[derive(Debug)]
 821pub struct DocumentHighlight {
 822    pub range: Range<language::Anchor>,
 823    pub kind: DocumentHighlightKind,
 824}
 825
 826#[derive(Clone, Debug)]
 827pub struct Symbol {
 828    pub language_server_name: LanguageServerName,
 829    pub source_worktree_id: WorktreeId,
 830    pub source_language_server_id: LanguageServerId,
 831    pub path: SymbolLocation,
 832    pub label: CodeLabel,
 833    pub name: String,
 834    pub kind: lsp::SymbolKind,
 835    pub range: Range<Unclipped<PointUtf16>>,
 836    pub container_name: Option<String>,
 837}
 838
 839#[derive(Clone, Debug)]
 840pub struct DocumentSymbol {
 841    pub name: String,
 842    pub kind: lsp::SymbolKind,
 843    pub range: Range<Unclipped<PointUtf16>>,
 844    pub selection_range: Range<Unclipped<PointUtf16>>,
 845    pub children: Vec<DocumentSymbol>,
 846}
 847
 848#[derive(Clone, Debug, PartialEq)]
 849pub struct HoverBlock {
 850    pub text: String,
 851    pub kind: HoverBlockKind,
 852}
 853
 854#[derive(Clone, Debug, PartialEq, Eq)]
 855pub enum HoverBlockKind {
 856    PlainText,
 857    Markdown,
 858    Code { language: String },
 859}
 860
 861#[derive(Debug, Clone)]
 862pub struct Hover {
 863    pub contents: Vec<HoverBlock>,
 864    pub range: Option<Range<language::Anchor>>,
 865    pub language: Option<Arc<Language>>,
 866}
 867
 868impl Hover {
 869    pub fn is_empty(&self) -> bool {
 870        self.contents.iter().all(|block| block.text.is_empty())
 871    }
 872}
 873
 874enum EntitySubscription {
 875    Project(PendingEntitySubscription<Project>),
 876    BufferStore(PendingEntitySubscription<BufferStore>),
 877    GitStore(PendingEntitySubscription<GitStore>),
 878    WorktreeStore(PendingEntitySubscription<WorktreeStore>),
 879    LspStore(PendingEntitySubscription<LspStore>),
 880    SettingsObserver(PendingEntitySubscription<SettingsObserver>),
 881    DapStore(PendingEntitySubscription<DapStore>),
 882    BreakpointStore(PendingEntitySubscription<BreakpointStore>),
 883}
 884
 885#[derive(Debug, Clone)]
 886pub struct DirectoryItem {
 887    pub path: PathBuf,
 888    pub is_dir: bool,
 889}
 890
 891#[derive(Clone, Debug, PartialEq)]
 892pub struct DocumentColor {
 893    pub lsp_range: lsp::Range,
 894    pub color: lsp::Color,
 895    pub resolved: bool,
 896    pub color_presentations: Vec<ColorPresentation>,
 897}
 898
 899impl Eq for DocumentColor {}
 900
 901impl std::hash::Hash for DocumentColor {
 902    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
 903        self.lsp_range.hash(state);
 904        self.color.red.to_bits().hash(state);
 905        self.color.green.to_bits().hash(state);
 906        self.color.blue.to_bits().hash(state);
 907        self.color.alpha.to_bits().hash(state);
 908        self.resolved.hash(state);
 909        self.color_presentations.hash(state);
 910    }
 911}
 912
 913#[derive(Clone, Debug, PartialEq, Eq)]
 914pub struct ColorPresentation {
 915    pub label: SharedString,
 916    pub text_edit: Option<lsp::TextEdit>,
 917    pub additional_text_edits: Vec<lsp::TextEdit>,
 918}
 919
 920impl std::hash::Hash for ColorPresentation {
 921    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
 922        self.label.hash(state);
 923        if let Some(ref edit) = self.text_edit {
 924            edit.range.hash(state);
 925            edit.new_text.hash(state);
 926        }
 927        self.additional_text_edits.len().hash(state);
 928        for edit in &self.additional_text_edits {
 929            edit.range.hash(state);
 930            edit.new_text.hash(state);
 931        }
 932    }
 933}
 934
 935#[derive(Clone)]
 936pub enum DirectoryLister {
 937    Project(Entity<Project>),
 938    Local(Entity<Project>, Arc<dyn Fs>),
 939}
 940
 941impl std::fmt::Debug for DirectoryLister {
 942    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 943        match self {
 944            DirectoryLister::Project(project) => {
 945                write!(f, "DirectoryLister::Project({project:?})")
 946            }
 947            DirectoryLister::Local(project, _) => {
 948                write!(f, "DirectoryLister::Local({project:?})")
 949            }
 950        }
 951    }
 952}
 953
 954impl DirectoryLister {
 955    pub fn is_local(&self, cx: &App) -> bool {
 956        match self {
 957            DirectoryLister::Local(..) => true,
 958            DirectoryLister::Project(project) => project.read(cx).is_local(),
 959        }
 960    }
 961
 962    pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &App) -> Cow<'a, str> {
 963        if self.is_local(cx) {
 964            shellexpand::tilde(path)
 965        } else {
 966            Cow::from(path)
 967        }
 968    }
 969
 970    pub fn default_query(&self, cx: &mut App) -> String {
 971        let project = match self {
 972            DirectoryLister::Project(project) => project,
 973            DirectoryLister::Local(project, _) => project,
 974        }
 975        .read(cx);
 976        let path_style = project.path_style(cx);
 977        project
 978            .visible_worktrees(cx)
 979            .next()
 980            .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().into_owned())
 981            .or_else(|| std::env::home_dir().map(|dir| dir.to_string_lossy().into_owned()))
 982            .map(|mut s| {
 983                s.push_str(path_style.primary_separator());
 984                s
 985            })
 986            .unwrap_or_else(|| {
 987                if path_style.is_windows() {
 988                    "C:\\"
 989                } else {
 990                    "~/"
 991                }
 992                .to_string()
 993            })
 994    }
 995
 996    pub fn list_directory(&self, path: String, cx: &mut App) -> Task<Result<Vec<DirectoryItem>>> {
 997        match self {
 998            DirectoryLister::Project(project) => {
 999                project.update(cx, |project, cx| project.list_directory(path, cx))
1000            }
1001            DirectoryLister::Local(_, fs) => {
1002                let fs = fs.clone();
1003                cx.background_spawn(async move {
1004                    let mut results = vec![];
1005                    let expanded = shellexpand::tilde(&path);
1006                    let query = Path::new(expanded.as_ref());
1007                    let mut response = fs.read_dir(query).await?;
1008                    while let Some(path) = response.next().await {
1009                        let path = path?;
1010                        if let Some(file_name) = path.file_name() {
1011                            results.push(DirectoryItem {
1012                                path: PathBuf::from(file_name.to_os_string()),
1013                                is_dir: fs.is_dir(&path).await,
1014                            });
1015                        }
1016                    }
1017                    Ok(results)
1018                })
1019            }
1020        }
1021    }
1022
1023    pub fn path_style(&self, cx: &App) -> PathStyle {
1024        match self {
1025            Self::Local(project, ..) | Self::Project(project, ..) => {
1026                project.read(cx).path_style(cx)
1027            }
1028        }
1029    }
1030}
1031
1032#[cfg(feature = "test-support")]
1033pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
1034    trigger_kind: lsp::CompletionTriggerKind::INVOKED,
1035    trigger_character: None,
1036};
1037
1038/// An LSP diagnostics associated with a certain language server.
1039#[derive(Clone, Debug, Default)]
1040pub enum LspPullDiagnostics {
1041    #[default]
1042    Default,
1043    Response {
1044        /// The id of the language server that produced diagnostics.
1045        server_id: LanguageServerId,
1046        /// URI of the resource,
1047        uri: lsp::Uri,
1048        /// The ID provided by the dynamic registration that produced diagnostics.
1049        registration_id: Option<SharedString>,
1050        /// The diagnostics produced by this language server.
1051        diagnostics: PulledDiagnostics,
1052    },
1053}
1054
1055#[derive(Clone, Debug)]
1056pub enum PulledDiagnostics {
1057    Unchanged {
1058        /// An ID the current pulled batch for this file.
1059        /// If given, can be used to query workspace diagnostics partially.
1060        result_id: SharedString,
1061    },
1062    Changed {
1063        result_id: Option<SharedString>,
1064        diagnostics: Vec<lsp::Diagnostic>,
1065    },
1066}
1067
1068/// Whether to disable all AI features in Zed.
1069///
1070/// Default: false
1071#[derive(Copy, Clone, Debug, RegisterSetting)]
1072pub struct DisableAiSettings {
1073    pub disable_ai: bool,
1074}
1075
1076impl settings::Settings for DisableAiSettings {
1077    fn from_settings(content: &settings::SettingsContent) -> Self {
1078        Self {
1079            disable_ai: content.project.disable_ai.unwrap().0,
1080        }
1081    }
1082}
1083
1084impl DisableAiSettings {
1085    /// Returns whether AI is disabled for the given file.
1086    ///
1087    /// This checks the project-level settings for the file's worktree,
1088    /// allowing `disable_ai` to be configured per-project in `.zed/settings.json`.
1089    pub fn is_ai_disabled_for_buffer(buffer: Option<&Entity<Buffer>>, cx: &App) -> bool {
1090        Self::is_ai_disabled_for_file(buffer.and_then(|buffer| buffer.read(cx).file()), cx)
1091    }
1092
1093    pub fn is_ai_disabled_for_file(file: Option<&Arc<dyn language::File>>, cx: &App) -> bool {
1094        let location = file.map(|f| settings::SettingsLocation {
1095            worktree_id: f.worktree_id(cx),
1096            path: f.path().as_ref(),
1097        });
1098        Self::get(location, cx).disable_ai
1099    }
1100}
1101
1102impl Project {
1103    pub fn init(client: &Arc<Client>, cx: &mut App) {
1104        connection_manager::init(client.clone(), cx);
1105
1106        let client: AnyProtoClient = client.clone().into();
1107        client.add_entity_message_handler(Self::handle_add_collaborator);
1108        client.add_entity_message_handler(Self::handle_update_project_collaborator);
1109        client.add_entity_message_handler(Self::handle_remove_collaborator);
1110        client.add_entity_message_handler(Self::handle_update_project);
1111        client.add_entity_message_handler(Self::handle_unshare_project);
1112        client.add_entity_request_handler(Self::handle_update_buffer);
1113        client.add_entity_message_handler(Self::handle_update_worktree);
1114        client.add_entity_request_handler(Self::handle_synchronize_buffers);
1115
1116        client.add_entity_request_handler(Self::handle_search_candidate_buffers);
1117        client.add_entity_request_handler(Self::handle_open_buffer_by_id);
1118        client.add_entity_request_handler(Self::handle_open_buffer_by_path);
1119        client.add_entity_request_handler(Self::handle_open_new_buffer);
1120        client.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1121        client.add_entity_message_handler(Self::handle_toggle_lsp_logs);
1122        client.add_entity_message_handler(Self::handle_create_image_for_peer);
1123        client.add_entity_request_handler(Self::handle_find_search_candidates_chunk);
1124        client.add_entity_message_handler(Self::handle_find_search_candidates_cancel);
1125        client.add_entity_message_handler(Self::handle_create_file_for_peer);
1126
1127        WorktreeStore::init(&client);
1128        BufferStore::init(&client);
1129        LspStore::init(&client);
1130        GitStore::init(&client);
1131        SettingsObserver::init(&client);
1132        TaskStore::init(Some(&client));
1133        ToolchainStore::init(&client);
1134        DapStore::init(&client, cx);
1135        BreakpointStore::init(&client);
1136        context_server_store::init(cx);
1137    }
1138
1139    pub fn local(
1140        client: Arc<Client>,
1141        node: NodeRuntime,
1142        user_store: Entity<UserStore>,
1143        languages: Arc<LanguageRegistry>,
1144        fs: Arc<dyn Fs>,
1145        env: Option<HashMap<String, String>>,
1146        flags: LocalProjectFlags,
1147        cx: &mut App,
1148    ) -> Entity<Self> {
1149        cx.new(|cx: &mut Context<Self>| {
1150            let (tx, rx) = mpsc::unbounded();
1151            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1152                .detach();
1153            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1154            let worktree_store =
1155                cx.new(|cx| WorktreeStore::local(false, fs.clone(), WorktreeIdCounter::get(cx)));
1156            if flags.init_worktree_trust {
1157                trusted_worktrees::track_worktree_trust(
1158                    worktree_store.clone(),
1159                    None,
1160                    None,
1161                    None,
1162                    cx,
1163                );
1164            }
1165            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1166                .detach();
1167
1168            let weak_self = cx.weak_entity();
1169            let context_server_store = cx.new(|cx| {
1170                ContextServerStore::local(
1171                    worktree_store.clone(),
1172                    Some(weak_self.clone()),
1173                    false,
1174                    cx,
1175                )
1176            });
1177
1178            let environment = cx.new(|cx| {
1179                ProjectEnvironment::new(env, worktree_store.downgrade(), None, false, cx)
1180            });
1181            let manifest_tree = ManifestTree::new(worktree_store.clone(), cx);
1182            let toolchain_store = cx.new(|cx| {
1183                ToolchainStore::local(
1184                    languages.clone(),
1185                    worktree_store.clone(),
1186                    environment.clone(),
1187                    manifest_tree.clone(),
1188                    fs.clone(),
1189                    cx,
1190                )
1191            });
1192
1193            let buffer_store = cx.new(|cx| BufferStore::local(worktree_store.clone(), cx));
1194            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1195                .detach();
1196
1197            let breakpoint_store =
1198                cx.new(|_| BreakpointStore::local(worktree_store.clone(), buffer_store.clone()));
1199
1200            let dap_store = cx.new(|cx| {
1201                DapStore::new_local(
1202                    client.http_client(),
1203                    node.clone(),
1204                    fs.clone(),
1205                    environment.clone(),
1206                    toolchain_store.read(cx).as_language_toolchain_store(),
1207                    worktree_store.clone(),
1208                    breakpoint_store.clone(),
1209                    false,
1210                    cx,
1211                )
1212            });
1213            cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1214
1215            let image_store = cx.new(|cx| ImageStore::local(worktree_store.clone(), cx));
1216            cx.subscribe(&image_store, Self::on_image_store_event)
1217                .detach();
1218
1219            let prettier_store = cx.new(|cx| {
1220                PrettierStore::new(
1221                    node.clone(),
1222                    fs.clone(),
1223                    languages.clone(),
1224                    worktree_store.clone(),
1225                    cx,
1226                )
1227            });
1228
1229            let task_store = cx.new(|cx| {
1230                TaskStore::local(
1231                    buffer_store.downgrade(),
1232                    worktree_store.clone(),
1233                    toolchain_store.read(cx).as_language_toolchain_store(),
1234                    environment.clone(),
1235                    cx,
1236                )
1237            });
1238
1239            let settings_observer = cx.new(|cx| {
1240                SettingsObserver::new_local(
1241                    fs.clone(),
1242                    worktree_store.clone(),
1243                    task_store.clone(),
1244                    flags.watch_global_configs,
1245                    cx,
1246                )
1247            });
1248            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1249                .detach();
1250
1251            let lsp_store = cx.new(|cx| {
1252                LspStore::new_local(
1253                    buffer_store.clone(),
1254                    worktree_store.clone(),
1255                    prettier_store.clone(),
1256                    toolchain_store
1257                        .read(cx)
1258                        .as_local_store()
1259                        .expect("Toolchain store to be local")
1260                        .clone(),
1261                    environment.clone(),
1262                    manifest_tree,
1263                    languages.clone(),
1264                    client.http_client(),
1265                    fs.clone(),
1266                    cx,
1267                )
1268            });
1269
1270            let git_store = cx.new(|cx| {
1271                GitStore::local(
1272                    &worktree_store,
1273                    buffer_store.clone(),
1274                    environment.clone(),
1275                    fs.clone(),
1276                    cx,
1277                )
1278            });
1279
1280            let agent_server_store = cx.new(|cx| {
1281                AgentServerStore::local(
1282                    node.clone(),
1283                    fs.clone(),
1284                    environment.clone(),
1285                    client.http_client(),
1286                    cx,
1287                )
1288            });
1289
1290            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1291
1292            Self {
1293                buffer_ordered_messages_tx: tx,
1294                collaborators: Default::default(),
1295                worktree_store,
1296                buffer_store,
1297                image_store,
1298                lsp_store,
1299                context_server_store,
1300                join_project_response_message_id: 0,
1301                client_state: ProjectClientState::Local,
1302                git_store,
1303                client_subscriptions: Vec::new(),
1304                _subscriptions: vec![cx.on_release(Self::release)],
1305                active_entry: None,
1306                snippets,
1307                languages,
1308                collab_client: client,
1309                task_store,
1310                user_store,
1311                settings_observer,
1312                fs,
1313                remote_client: None,
1314                breakpoint_store,
1315                dap_store,
1316                agent_server_store,
1317
1318                buffers_needing_diff: Default::default(),
1319                git_diff_debouncer: DebouncedDelay::new(),
1320                terminals: Terminals {
1321                    local_handles: Vec::new(),
1322                },
1323                node: Some(node),
1324                search_history: Self::new_search_history(),
1325                environment,
1326                remotely_created_models: Default::default(),
1327
1328                search_included_history: Self::new_search_history(),
1329                search_excluded_history: Self::new_search_history(),
1330
1331                toolchain_store: Some(toolchain_store),
1332
1333                agent_location: None,
1334                downloading_files: Default::default(),
1335            }
1336        })
1337    }
1338
1339    pub fn remote(
1340        remote: Entity<RemoteClient>,
1341        client: Arc<Client>,
1342        node: NodeRuntime,
1343        user_store: Entity<UserStore>,
1344        languages: Arc<LanguageRegistry>,
1345        fs: Arc<dyn Fs>,
1346        init_worktree_trust: bool,
1347        cx: &mut App,
1348    ) -> Entity<Self> {
1349        cx.new(|cx: &mut Context<Self>| {
1350            let (tx, rx) = mpsc::unbounded();
1351            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1352                .detach();
1353            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1354
1355            let (remote_proto, path_style, connection_options) =
1356                remote.read_with(cx, |remote, _| {
1357                    (
1358                        remote.proto_client(),
1359                        remote.path_style(),
1360                        remote.connection_options(),
1361                    )
1362                });
1363            let worktree_store = cx.new(|cx| {
1364                WorktreeStore::remote(
1365                    false,
1366                    remote_proto.clone(),
1367                    REMOTE_SERVER_PROJECT_ID,
1368                    path_style,
1369                    WorktreeIdCounter::get(cx),
1370                )
1371            });
1372
1373            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1374                .detach();
1375            if init_worktree_trust {
1376                trusted_worktrees::track_worktree_trust(
1377                    worktree_store.clone(),
1378                    Some(RemoteHostLocation::from(connection_options)),
1379                    None,
1380                    Some((remote_proto.clone(), ProjectId(REMOTE_SERVER_PROJECT_ID))),
1381                    cx,
1382                );
1383            }
1384
1385            let weak_self = cx.weak_entity();
1386
1387            let buffer_store = cx.new(|cx| {
1388                BufferStore::remote(
1389                    worktree_store.clone(),
1390                    remote.read(cx).proto_client(),
1391                    REMOTE_SERVER_PROJECT_ID,
1392                    cx,
1393                )
1394            });
1395            let image_store = cx.new(|cx| {
1396                ImageStore::remote(
1397                    worktree_store.clone(),
1398                    remote.read(cx).proto_client(),
1399                    REMOTE_SERVER_PROJECT_ID,
1400                    cx,
1401                )
1402            });
1403            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1404                .detach();
1405            let toolchain_store = cx.new(|cx| {
1406                ToolchainStore::remote(
1407                    REMOTE_SERVER_PROJECT_ID,
1408                    worktree_store.clone(),
1409                    remote.read(cx).proto_client(),
1410                    cx,
1411                )
1412            });
1413
1414            let task_store = cx.new(|cx| {
1415                TaskStore::remote(
1416                    buffer_store.downgrade(),
1417                    worktree_store.clone(),
1418                    toolchain_store.read(cx).as_language_toolchain_store(),
1419                    remote.read(cx).proto_client(),
1420                    REMOTE_SERVER_PROJECT_ID,
1421                    cx,
1422                )
1423            });
1424
1425            let settings_observer = cx.new(|cx| {
1426                SettingsObserver::new_remote(
1427                    fs.clone(),
1428                    worktree_store.clone(),
1429                    task_store.clone(),
1430                    Some(remote_proto.clone()),
1431                    false,
1432                    cx,
1433                )
1434            });
1435            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1436                .detach();
1437
1438            let context_server_store = cx.new(|cx| {
1439                ContextServerStore::remote(
1440                    rpc::proto::REMOTE_SERVER_PROJECT_ID,
1441                    remote.clone(),
1442                    worktree_store.clone(),
1443                    Some(weak_self.clone()),
1444                    cx,
1445                )
1446            });
1447
1448            let environment = cx.new(|cx| {
1449                ProjectEnvironment::new(
1450                    None,
1451                    worktree_store.downgrade(),
1452                    Some(remote.downgrade()),
1453                    false,
1454                    cx,
1455                )
1456            });
1457
1458            let lsp_store = cx.new(|cx| {
1459                LspStore::new_remote(
1460                    buffer_store.clone(),
1461                    worktree_store.clone(),
1462                    languages.clone(),
1463                    remote_proto.clone(),
1464                    REMOTE_SERVER_PROJECT_ID,
1465                    cx,
1466                )
1467            });
1468            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1469
1470            let breakpoint_store = cx.new(|_| {
1471                BreakpointStore::remote(
1472                    REMOTE_SERVER_PROJECT_ID,
1473                    remote_proto.clone(),
1474                    buffer_store.clone(),
1475                    worktree_store.clone(),
1476                )
1477            });
1478
1479            let dap_store = cx.new(|cx| {
1480                DapStore::new_remote(
1481                    REMOTE_SERVER_PROJECT_ID,
1482                    remote.clone(),
1483                    breakpoint_store.clone(),
1484                    worktree_store.clone(),
1485                    node.clone(),
1486                    client.http_client(),
1487                    fs.clone(),
1488                    cx,
1489                )
1490            });
1491
1492            let git_store = cx.new(|cx| {
1493                GitStore::remote(
1494                    &worktree_store,
1495                    buffer_store.clone(),
1496                    remote_proto.clone(),
1497                    REMOTE_SERVER_PROJECT_ID,
1498                    cx,
1499                )
1500            });
1501
1502            let agent_server_store =
1503                cx.new(|_| AgentServerStore::remote(REMOTE_SERVER_PROJECT_ID, remote.clone()));
1504
1505            cx.subscribe(&remote, Self::on_remote_client_event).detach();
1506
1507            let this = Self {
1508                buffer_ordered_messages_tx: tx,
1509                collaborators: Default::default(),
1510                worktree_store,
1511                buffer_store,
1512                image_store,
1513                lsp_store,
1514                context_server_store,
1515                breakpoint_store,
1516                dap_store,
1517                join_project_response_message_id: 0,
1518                client_state: ProjectClientState::Local,
1519                git_store,
1520                agent_server_store,
1521                client_subscriptions: Vec::new(),
1522                _subscriptions: vec![
1523                    cx.on_release(Self::release),
1524                    cx.on_app_quit(|this, cx| {
1525                        let shutdown = this.remote_client.take().and_then(|client| {
1526                            client.update(cx, |client, cx| {
1527                                client.shutdown_processes(
1528                                    Some(proto::ShutdownRemoteServer {}),
1529                                    cx.background_executor().clone(),
1530                                )
1531                            })
1532                        });
1533
1534                        cx.background_executor().spawn(async move {
1535                            if let Some(shutdown) = shutdown {
1536                                shutdown.await;
1537                            }
1538                        })
1539                    }),
1540                ],
1541                active_entry: None,
1542                snippets,
1543                languages,
1544                collab_client: client,
1545                task_store,
1546                user_store,
1547                settings_observer,
1548                fs,
1549                remote_client: Some(remote.clone()),
1550                buffers_needing_diff: Default::default(),
1551                git_diff_debouncer: DebouncedDelay::new(),
1552                terminals: Terminals {
1553                    local_handles: Vec::new(),
1554                },
1555                node: Some(node),
1556                search_history: Self::new_search_history(),
1557                environment,
1558                remotely_created_models: Default::default(),
1559
1560                search_included_history: Self::new_search_history(),
1561                search_excluded_history: Self::new_search_history(),
1562
1563                toolchain_store: Some(toolchain_store),
1564                agent_location: None,
1565                downloading_files: Default::default(),
1566            };
1567
1568            // remote server -> local machine handlers
1569            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &cx.entity());
1570            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.buffer_store);
1571            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.worktree_store);
1572            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.lsp_store);
1573            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.dap_store);
1574            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.breakpoint_store);
1575            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.settings_observer);
1576            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.git_store);
1577            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.agent_server_store);
1578
1579            remote_proto.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1580            remote_proto.add_entity_message_handler(Self::handle_create_image_for_peer);
1581            remote_proto.add_entity_message_handler(Self::handle_create_file_for_peer);
1582            remote_proto.add_entity_message_handler(Self::handle_update_worktree);
1583            remote_proto.add_entity_message_handler(Self::handle_update_project);
1584            remote_proto.add_entity_message_handler(Self::handle_toast);
1585            remote_proto.add_entity_request_handler(Self::handle_language_server_prompt_request);
1586            remote_proto.add_entity_message_handler(Self::handle_hide_toast);
1587            remote_proto.add_entity_request_handler(Self::handle_update_buffer_from_remote_server);
1588            remote_proto.add_entity_request_handler(Self::handle_trust_worktrees);
1589            remote_proto.add_entity_request_handler(Self::handle_restrict_worktrees);
1590            remote_proto.add_entity_request_handler(Self::handle_find_search_candidates_chunk);
1591
1592            remote_proto.add_entity_message_handler(Self::handle_find_search_candidates_cancel);
1593            BufferStore::init(&remote_proto);
1594            WorktreeStore::init_remote(&remote_proto);
1595            LspStore::init(&remote_proto);
1596            SettingsObserver::init(&remote_proto);
1597            TaskStore::init(Some(&remote_proto));
1598            ToolchainStore::init(&remote_proto);
1599            DapStore::init(&remote_proto, cx);
1600            BreakpointStore::init(&remote_proto);
1601            GitStore::init(&remote_proto);
1602            AgentServerStore::init_remote(&remote_proto);
1603
1604            this
1605        })
1606    }
1607
1608    pub async fn in_room(
1609        remote_id: u64,
1610        client: Arc<Client>,
1611        user_store: Entity<UserStore>,
1612        languages: Arc<LanguageRegistry>,
1613        fs: Arc<dyn Fs>,
1614        cx: AsyncApp,
1615    ) -> Result<Entity<Self>> {
1616        client.connect(true, &cx).await.into_response()?;
1617
1618        let subscriptions = [
1619            EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
1620            EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
1621            EntitySubscription::GitStore(client.subscribe_to_entity::<GitStore>(remote_id)?),
1622            EntitySubscription::WorktreeStore(
1623                client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
1624            ),
1625            EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
1626            EntitySubscription::SettingsObserver(
1627                client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
1628            ),
1629            EntitySubscription::DapStore(client.subscribe_to_entity::<DapStore>(remote_id)?),
1630            EntitySubscription::BreakpointStore(
1631                client.subscribe_to_entity::<BreakpointStore>(remote_id)?,
1632            ),
1633        ];
1634        let committer = get_git_committer(&cx).await;
1635        let response = client
1636            .request_envelope(proto::JoinProject {
1637                project_id: remote_id,
1638                committer_email: committer.email,
1639                committer_name: committer.name,
1640            })
1641            .await?;
1642        Self::from_join_project_response(
1643            response,
1644            subscriptions,
1645            client,
1646            false,
1647            user_store,
1648            languages,
1649            fs,
1650            cx,
1651        )
1652        .await
1653    }
1654
1655    async fn from_join_project_response(
1656        response: TypedEnvelope<proto::JoinProjectResponse>,
1657        subscriptions: [EntitySubscription; 8],
1658        client: Arc<Client>,
1659        run_tasks: bool,
1660        user_store: Entity<UserStore>,
1661        languages: Arc<LanguageRegistry>,
1662        fs: Arc<dyn Fs>,
1663        mut cx: AsyncApp,
1664    ) -> Result<Entity<Self>> {
1665        let remote_id = response.payload.project_id;
1666        let role = response.payload.role();
1667
1668        let path_style = if response.payload.windows_paths {
1669            PathStyle::Windows
1670        } else {
1671            PathStyle::Posix
1672        };
1673
1674        let worktree_store = cx.new(|cx| {
1675            WorktreeStore::remote(
1676                true,
1677                client.clone().into(),
1678                response.payload.project_id,
1679                path_style,
1680                WorktreeIdCounter::get(cx),
1681            )
1682        });
1683        let buffer_store = cx.new(|cx| {
1684            BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1685        });
1686        let image_store = cx.new(|cx| {
1687            ImageStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1688        });
1689
1690        let environment =
1691            cx.new(|cx| ProjectEnvironment::new(None, worktree_store.downgrade(), None, true, cx));
1692        let breakpoint_store = cx.new(|_| {
1693            BreakpointStore::remote(
1694                remote_id,
1695                client.clone().into(),
1696                buffer_store.clone(),
1697                worktree_store.clone(),
1698            )
1699        });
1700        let dap_store = cx.new(|cx| {
1701            DapStore::new_collab(
1702                remote_id,
1703                client.clone().into(),
1704                breakpoint_store.clone(),
1705                worktree_store.clone(),
1706                fs.clone(),
1707                cx,
1708            )
1709        });
1710
1711        let lsp_store = cx.new(|cx| {
1712            LspStore::new_remote(
1713                buffer_store.clone(),
1714                worktree_store.clone(),
1715                languages.clone(),
1716                client.clone().into(),
1717                remote_id,
1718                cx,
1719            )
1720        });
1721
1722        let task_store = cx.new(|cx| {
1723            if run_tasks {
1724                TaskStore::remote(
1725                    buffer_store.downgrade(),
1726                    worktree_store.clone(),
1727                    Arc::new(EmptyToolchainStore),
1728                    client.clone().into(),
1729                    remote_id,
1730                    cx,
1731                )
1732            } else {
1733                TaskStore::Noop
1734            }
1735        });
1736
1737        let settings_observer = cx.new(|cx| {
1738            SettingsObserver::new_remote(
1739                fs.clone(),
1740                worktree_store.clone(),
1741                task_store.clone(),
1742                None,
1743                true,
1744                cx,
1745            )
1746        });
1747
1748        let git_store = cx.new(|cx| {
1749            GitStore::remote(
1750                // In this remote case we pass None for the environment
1751                &worktree_store,
1752                buffer_store.clone(),
1753                client.clone().into(),
1754                remote_id,
1755                cx,
1756            )
1757        });
1758
1759        let agent_server_store = cx.new(|_cx| AgentServerStore::collab());
1760        let replica_id = ReplicaId::new(response.payload.replica_id as u16);
1761
1762        let project = cx.new(|cx| {
1763            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1764
1765            let weak_self = cx.weak_entity();
1766            let context_server_store = cx.new(|cx| {
1767                ContextServerStore::local(worktree_store.clone(), Some(weak_self), false, cx)
1768            });
1769
1770            let mut worktrees = Vec::new();
1771            for worktree in response.payload.worktrees {
1772                let worktree = Worktree::remote(
1773                    remote_id,
1774                    replica_id,
1775                    worktree,
1776                    client.clone().into(),
1777                    path_style,
1778                    cx,
1779                );
1780                worktrees.push(worktree);
1781            }
1782
1783            let (tx, rx) = mpsc::unbounded();
1784            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1785                .detach();
1786
1787            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1788                .detach();
1789
1790            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1791                .detach();
1792            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1793            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1794                .detach();
1795
1796            cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1797
1798            let mut project = Self {
1799                buffer_ordered_messages_tx: tx,
1800                buffer_store: buffer_store.clone(),
1801                image_store,
1802                worktree_store: worktree_store.clone(),
1803                lsp_store: lsp_store.clone(),
1804                context_server_store,
1805                active_entry: None,
1806                collaborators: Default::default(),
1807                join_project_response_message_id: response.message_id,
1808                languages,
1809                user_store: user_store.clone(),
1810                task_store,
1811                snippets,
1812                fs,
1813                remote_client: None,
1814                settings_observer: settings_observer.clone(),
1815                client_subscriptions: Default::default(),
1816                _subscriptions: vec![cx.on_release(Self::release)],
1817                collab_client: client.clone(),
1818                client_state: ProjectClientState::Remote {
1819                    sharing_has_stopped: false,
1820                    capability: Capability::ReadWrite,
1821                    remote_id,
1822                    replica_id,
1823                },
1824                breakpoint_store: breakpoint_store.clone(),
1825                dap_store: dap_store.clone(),
1826                git_store: git_store.clone(),
1827                agent_server_store,
1828                buffers_needing_diff: Default::default(),
1829                git_diff_debouncer: DebouncedDelay::new(),
1830                terminals: Terminals {
1831                    local_handles: Vec::new(),
1832                },
1833                node: None,
1834                search_history: Self::new_search_history(),
1835                search_included_history: Self::new_search_history(),
1836                search_excluded_history: Self::new_search_history(),
1837                environment,
1838                remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1839                toolchain_store: None,
1840                agent_location: None,
1841                downloading_files: Default::default(),
1842            };
1843            project.set_role(role, cx);
1844            for worktree in worktrees {
1845                project.add_worktree(&worktree, cx);
1846            }
1847            project
1848        });
1849
1850        let weak_project = project.downgrade();
1851        lsp_store.update(&mut cx, |lsp_store, cx| {
1852            lsp_store.set_language_server_statuses_from_proto(
1853                weak_project,
1854                response.payload.language_servers,
1855                response.payload.language_server_capabilities,
1856                cx,
1857            );
1858        });
1859
1860        let subscriptions = subscriptions
1861            .into_iter()
1862            .map(|s| match s {
1863                EntitySubscription::BufferStore(subscription) => {
1864                    subscription.set_entity(&buffer_store, &cx)
1865                }
1866                EntitySubscription::WorktreeStore(subscription) => {
1867                    subscription.set_entity(&worktree_store, &cx)
1868                }
1869                EntitySubscription::GitStore(subscription) => {
1870                    subscription.set_entity(&git_store, &cx)
1871                }
1872                EntitySubscription::SettingsObserver(subscription) => {
1873                    subscription.set_entity(&settings_observer, &cx)
1874                }
1875                EntitySubscription::Project(subscription) => subscription.set_entity(&project, &cx),
1876                EntitySubscription::LspStore(subscription) => {
1877                    subscription.set_entity(&lsp_store, &cx)
1878                }
1879                EntitySubscription::DapStore(subscription) => {
1880                    subscription.set_entity(&dap_store, &cx)
1881                }
1882                EntitySubscription::BreakpointStore(subscription) => {
1883                    subscription.set_entity(&breakpoint_store, &cx)
1884                }
1885            })
1886            .collect::<Vec<_>>();
1887
1888        let user_ids = response
1889            .payload
1890            .collaborators
1891            .iter()
1892            .map(|peer| peer.user_id)
1893            .collect();
1894        user_store
1895            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
1896            .await?;
1897
1898        project.update(&mut cx, |this, cx| {
1899            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1900            this.client_subscriptions.extend(subscriptions);
1901            anyhow::Ok(())
1902        })?;
1903
1904        Ok(project)
1905    }
1906
1907    fn new_search_history() -> SearchHistory {
1908        SearchHistory::new(
1909            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1910            search_history::QueryInsertionBehavior::AlwaysInsert,
1911        )
1912    }
1913
1914    fn release(&mut self, cx: &mut App) {
1915        if let Some(client) = self.remote_client.take() {
1916            let shutdown = client.update(cx, |client, cx| {
1917                client.shutdown_processes(
1918                    Some(proto::ShutdownRemoteServer {}),
1919                    cx.background_executor().clone(),
1920                )
1921            });
1922
1923            cx.background_spawn(async move {
1924                if let Some(shutdown) = shutdown {
1925                    shutdown.await;
1926                }
1927            })
1928            .detach()
1929        }
1930
1931        match &self.client_state {
1932            ProjectClientState::Local => {}
1933            ProjectClientState::Shared { .. } => {
1934                let _ = self.unshare_internal(cx);
1935            }
1936            ProjectClientState::Remote { remote_id, .. } => {
1937                let _ = self.collab_client.send(proto::LeaveProject {
1938                    project_id: *remote_id,
1939                });
1940                self.disconnected_from_host_internal(cx);
1941            }
1942        }
1943    }
1944
1945    #[cfg(feature = "test-support")]
1946    pub fn client_subscriptions(&self) -> &Vec<client::Subscription> {
1947        &self.client_subscriptions
1948    }
1949
1950    #[cfg(feature = "test-support")]
1951    pub async fn example(
1952        root_paths: impl IntoIterator<Item = &Path>,
1953        cx: &mut AsyncApp,
1954    ) -> Entity<Project> {
1955        use clock::FakeSystemClock;
1956
1957        let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
1958        let languages = LanguageRegistry::test(cx.background_executor().clone());
1959        let clock = Arc::new(FakeSystemClock::new());
1960        let http_client = http_client::FakeHttpClient::with_404_response();
1961        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1962        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1963        let project = cx.update(|cx| {
1964            Project::local(
1965                client,
1966                node_runtime::NodeRuntime::unavailable(),
1967                user_store,
1968                Arc::new(languages),
1969                fs,
1970                None,
1971                LocalProjectFlags {
1972                    init_worktree_trust: false,
1973                    ..Default::default()
1974                },
1975                cx,
1976            )
1977        });
1978        for path in root_paths {
1979            let (tree, _): (Entity<Worktree>, _) = project
1980                .update(cx, |project, cx| {
1981                    project.find_or_create_worktree(path, true, cx)
1982                })
1983                .await
1984                .unwrap();
1985            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1986                .await;
1987        }
1988        project
1989    }
1990
1991    #[cfg(feature = "test-support")]
1992    pub async fn test(
1993        fs: Arc<dyn Fs>,
1994        root_paths: impl IntoIterator<Item = &Path>,
1995        cx: &mut gpui::TestAppContext,
1996    ) -> Entity<Project> {
1997        Self::test_project(fs, root_paths, false, cx).await
1998    }
1999
2000    #[cfg(feature = "test-support")]
2001    pub async fn test_with_worktree_trust(
2002        fs: Arc<dyn Fs>,
2003        root_paths: impl IntoIterator<Item = &Path>,
2004        cx: &mut gpui::TestAppContext,
2005    ) -> Entity<Project> {
2006        Self::test_project(fs, root_paths, true, cx).await
2007    }
2008
2009    #[cfg(feature = "test-support")]
2010    async fn test_project(
2011        fs: Arc<dyn Fs>,
2012        root_paths: impl IntoIterator<Item = &Path>,
2013        init_worktree_trust: bool,
2014        cx: &mut gpui::TestAppContext,
2015    ) -> Entity<Project> {
2016        use clock::FakeSystemClock;
2017
2018        let languages = LanguageRegistry::test(cx.executor());
2019        let clock = Arc::new(FakeSystemClock::new());
2020        let http_client = http_client::FakeHttpClient::with_404_response();
2021        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
2022        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
2023        let project = cx.update(|cx| {
2024            Project::local(
2025                client,
2026                node_runtime::NodeRuntime::unavailable(),
2027                user_store,
2028                Arc::new(languages),
2029                fs,
2030                None,
2031                LocalProjectFlags {
2032                    init_worktree_trust,
2033                    ..Default::default()
2034                },
2035                cx,
2036            )
2037        });
2038        for path in root_paths {
2039            let (tree, _) = project
2040                .update(cx, |project, cx| {
2041                    project.find_or_create_worktree(path, true, cx)
2042                })
2043                .await
2044                .unwrap();
2045
2046            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
2047                .await;
2048        }
2049        project
2050    }
2051
2052    #[inline]
2053    pub fn dap_store(&self) -> Entity<DapStore> {
2054        self.dap_store.clone()
2055    }
2056
2057    #[inline]
2058    pub fn breakpoint_store(&self) -> Entity<BreakpointStore> {
2059        self.breakpoint_store.clone()
2060    }
2061
2062    pub fn active_debug_session(&self, cx: &App) -> Option<(Entity<Session>, ActiveStackFrame)> {
2063        let active_position = self.breakpoint_store.read(cx).active_position()?;
2064        let session = self
2065            .dap_store
2066            .read(cx)
2067            .session_by_id(active_position.session_id)?;
2068        Some((session, active_position.clone()))
2069    }
2070
2071    #[inline]
2072    pub fn lsp_store(&self) -> Entity<LspStore> {
2073        self.lsp_store.clone()
2074    }
2075
2076    #[inline]
2077    pub fn worktree_store(&self) -> Entity<WorktreeStore> {
2078        self.worktree_store.clone()
2079    }
2080
2081    #[inline]
2082    pub fn context_server_store(&self) -> Entity<ContextServerStore> {
2083        self.context_server_store.clone()
2084    }
2085
2086    #[inline]
2087    pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
2088        self.buffer_store.read(cx).get(remote_id)
2089    }
2090
2091    #[inline]
2092    pub fn languages(&self) -> &Arc<LanguageRegistry> {
2093        &self.languages
2094    }
2095
2096    #[inline]
2097    pub fn client(&self) -> Arc<Client> {
2098        self.collab_client.clone()
2099    }
2100
2101    #[inline]
2102    pub fn remote_client(&self) -> Option<Entity<RemoteClient>> {
2103        self.remote_client.clone()
2104    }
2105
2106    #[inline]
2107    pub fn user_store(&self) -> Entity<UserStore> {
2108        self.user_store.clone()
2109    }
2110
2111    #[inline]
2112    pub fn node_runtime(&self) -> Option<&NodeRuntime> {
2113        self.node.as_ref()
2114    }
2115
2116    #[inline]
2117    pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
2118        self.buffer_store.read(cx).buffers().collect()
2119    }
2120
2121    #[inline]
2122    pub fn environment(&self) -> &Entity<ProjectEnvironment> {
2123        &self.environment
2124    }
2125
2126    #[inline]
2127    pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
2128        self.environment.read(cx).get_cli_environment()
2129    }
2130
2131    #[inline]
2132    pub fn peek_environment_error<'a>(&'a self, cx: &'a App) -> Option<&'a String> {
2133        self.environment.read(cx).peek_environment_error()
2134    }
2135
2136    #[inline]
2137    pub fn pop_environment_error(&mut self, cx: &mut Context<Self>) {
2138        self.environment.update(cx, |environment, _| {
2139            environment.pop_environment_error();
2140        });
2141    }
2142
2143    #[cfg(feature = "test-support")]
2144    #[inline]
2145    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
2146        self.buffer_store
2147            .read(cx)
2148            .get_by_path(&path.into())
2149            .is_some()
2150    }
2151
2152    #[inline]
2153    pub fn fs(&self) -> &Arc<dyn Fs> {
2154        &self.fs
2155    }
2156
2157    #[inline]
2158    pub fn remote_id(&self) -> Option<u64> {
2159        match self.client_state {
2160            ProjectClientState::Local => None,
2161            ProjectClientState::Shared { remote_id, .. }
2162            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
2163        }
2164    }
2165
2166    #[inline]
2167    pub fn supports_terminal(&self, _cx: &App) -> bool {
2168        if self.is_local() {
2169            return true;
2170        }
2171        if self.is_via_remote_server() {
2172            return true;
2173        }
2174
2175        false
2176    }
2177
2178    #[inline]
2179    pub fn remote_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
2180        self.remote_client
2181            .as_ref()
2182            .map(|remote| remote.read(cx).connection_state())
2183    }
2184
2185    #[inline]
2186    pub fn remote_connection_options(&self, cx: &App) -> Option<RemoteConnectionOptions> {
2187        self.remote_client
2188            .as_ref()
2189            .map(|remote| remote.read(cx).connection_options())
2190    }
2191
2192    /// Reveals the given path in the system file manager.
2193    ///
2194    /// On Windows with a WSL remote connection, this converts the POSIX path
2195    /// to a Windows UNC path before revealing.
2196    pub fn reveal_path(&self, path: &Path, cx: &mut Context<Self>) {
2197        #[cfg(target_os = "windows")]
2198        if let Some(RemoteConnectionOptions::Wsl(wsl_options)) = self.remote_connection_options(cx)
2199        {
2200            let path = path.to_path_buf();
2201            cx.spawn(async move |_, cx| {
2202                wsl_path_to_windows_path(&wsl_options, &path)
2203                    .await
2204                    .map(|windows_path| cx.update(|cx| cx.reveal_path(&windows_path)))
2205            })
2206            .detach_and_log_err(cx);
2207            return;
2208        }
2209
2210        cx.reveal_path(path);
2211    }
2212
2213    #[inline]
2214    pub fn replica_id(&self) -> ReplicaId {
2215        match self.client_state {
2216            ProjectClientState::Remote { replica_id, .. } => replica_id,
2217            _ => {
2218                if self.remote_client.is_some() {
2219                    ReplicaId::REMOTE_SERVER
2220                } else {
2221                    ReplicaId::LOCAL
2222                }
2223            }
2224        }
2225    }
2226
2227    #[inline]
2228    pub fn task_store(&self) -> &Entity<TaskStore> {
2229        &self.task_store
2230    }
2231
2232    #[inline]
2233    pub fn snippets(&self) -> &Entity<SnippetProvider> {
2234        &self.snippets
2235    }
2236
2237    #[inline]
2238    pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
2239        match kind {
2240            SearchInputKind::Query => &self.search_history,
2241            SearchInputKind::Include => &self.search_included_history,
2242            SearchInputKind::Exclude => &self.search_excluded_history,
2243        }
2244    }
2245
2246    #[inline]
2247    pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
2248        match kind {
2249            SearchInputKind::Query => &mut self.search_history,
2250            SearchInputKind::Include => &mut self.search_included_history,
2251            SearchInputKind::Exclude => &mut self.search_excluded_history,
2252        }
2253    }
2254
2255    #[inline]
2256    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
2257        &self.collaborators
2258    }
2259
2260    #[inline]
2261    pub fn host(&self) -> Option<&Collaborator> {
2262        self.collaborators.values().find(|c| c.is_host)
2263    }
2264
2265    #[inline]
2266    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
2267        self.worktree_store.update(cx, |store, _| {
2268            store.set_worktrees_reordered(worktrees_reordered);
2269        });
2270    }
2271
2272    /// Collect all worktrees, including ones that don't appear in the project panel
2273    #[inline]
2274    pub fn worktrees<'a>(
2275        &self,
2276        cx: &'a App,
2277    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2278        self.worktree_store.read(cx).worktrees()
2279    }
2280
2281    /// Collect all user-visible worktrees, the ones that appear in the project panel.
2282    #[inline]
2283    pub fn visible_worktrees<'a>(
2284        &'a self,
2285        cx: &'a App,
2286    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2287        self.worktree_store.read(cx).visible_worktrees(cx)
2288    }
2289
2290    #[inline]
2291    pub fn worktree_for_root_name(&self, root_name: &str, cx: &App) -> Option<Entity<Worktree>> {
2292        self.visible_worktrees(cx)
2293            .find(|tree| tree.read(cx).root_name() == root_name)
2294    }
2295
2296    #[inline]
2297    pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
2298        self.visible_worktrees(cx)
2299            .map(|tree| tree.read(cx).root_name().as_unix_str())
2300    }
2301
2302    #[inline]
2303    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
2304        self.worktree_store.read(cx).worktree_for_id(id, cx)
2305    }
2306
2307    pub fn worktree_for_entry(
2308        &self,
2309        entry_id: ProjectEntryId,
2310        cx: &App,
2311    ) -> Option<Entity<Worktree>> {
2312        self.worktree_store
2313            .read(cx)
2314            .worktree_for_entry(entry_id, cx)
2315    }
2316
2317    #[inline]
2318    pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
2319        self.worktree_for_entry(entry_id, cx)
2320            .map(|worktree| worktree.read(cx).id())
2321    }
2322
2323    /// Checks if the entry is the root of a worktree.
2324    #[inline]
2325    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
2326        self.worktree_for_entry(entry_id, cx)
2327            .map(|worktree| {
2328                worktree
2329                    .read(cx)
2330                    .root_entry()
2331                    .is_some_and(|e| e.id == entry_id)
2332            })
2333            .unwrap_or(false)
2334    }
2335
2336    #[inline]
2337    pub fn project_path_git_status(
2338        &self,
2339        project_path: &ProjectPath,
2340        cx: &App,
2341    ) -> Option<FileStatus> {
2342        self.git_store
2343            .read(cx)
2344            .project_path_git_status(project_path, cx)
2345    }
2346
2347    #[inline]
2348    pub fn visibility_for_paths(
2349        &self,
2350        paths: &[PathBuf],
2351        exclude_sub_dirs: bool,
2352        cx: &App,
2353    ) -> Option<bool> {
2354        paths
2355            .iter()
2356            .map(|path| self.visibility_for_path(path, exclude_sub_dirs, cx))
2357            .max()
2358            .flatten()
2359    }
2360
2361    pub fn visibility_for_path(
2362        &self,
2363        path: &Path,
2364        exclude_sub_dirs: bool,
2365        cx: &App,
2366    ) -> Option<bool> {
2367        let path = SanitizedPath::new(path).as_path();
2368        let path_style = self.path_style(cx);
2369        self.worktrees(cx)
2370            .filter_map(|worktree| {
2371                let worktree = worktree.read(cx);
2372                let abs_path = worktree.abs_path();
2373                let relative_path = path_style.strip_prefix(path, abs_path.as_ref());
2374                let is_dir = relative_path
2375                    .as_ref()
2376                    .and_then(|p| worktree.entry_for_path(p))
2377                    .is_some_and(|e| e.is_dir());
2378                // Don't exclude the worktree root itself, only actual subdirectories
2379                let is_subdir = relative_path
2380                    .as_ref()
2381                    .is_some_and(|p| !p.as_ref().as_unix_str().is_empty());
2382                let contains =
2383                    relative_path.is_some() && (!exclude_sub_dirs || !is_dir || !is_subdir);
2384                contains.then(|| worktree.is_visible())
2385            })
2386            .max()
2387    }
2388
2389    pub fn create_entry(
2390        &mut self,
2391        project_path: impl Into<ProjectPath>,
2392        is_directory: bool,
2393        cx: &mut Context<Self>,
2394    ) -> Task<Result<CreatedEntry>> {
2395        let project_path = project_path.into();
2396        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
2397            return Task::ready(Err(anyhow!(format!(
2398                "No worktree for path {project_path:?}"
2399            ))));
2400        };
2401        worktree.update(cx, |worktree, cx| {
2402            worktree.create_entry(project_path.path, is_directory, None, cx)
2403        })
2404    }
2405
2406    #[inline]
2407    pub fn copy_entry(
2408        &mut self,
2409        entry_id: ProjectEntryId,
2410        new_project_path: ProjectPath,
2411        cx: &mut Context<Self>,
2412    ) -> Task<Result<Option<Entry>>> {
2413        self.worktree_store.update(cx, |worktree_store, cx| {
2414            worktree_store.copy_entry(entry_id, new_project_path, cx)
2415        })
2416    }
2417
2418    /// Renames the project entry with given `entry_id`.
2419    ///
2420    /// `new_path` is a relative path to worktree root.
2421    /// If root entry is renamed then its new root name is used instead.
2422    pub fn rename_entry(
2423        &mut self,
2424        entry_id: ProjectEntryId,
2425        new_path: ProjectPath,
2426        cx: &mut Context<Self>,
2427    ) -> Task<Result<CreatedEntry>> {
2428        let worktree_store = self.worktree_store.clone();
2429        let Some((worktree, old_path, is_dir)) = worktree_store
2430            .read(cx)
2431            .worktree_and_entry_for_id(entry_id, cx)
2432            .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
2433        else {
2434            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
2435        };
2436
2437        let worktree_id = worktree.read(cx).id();
2438        let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
2439
2440        let lsp_store = self.lsp_store().downgrade();
2441        cx.spawn(async move |project, cx| {
2442            let (old_abs_path, new_abs_path) = {
2443                let root_path = worktree.read_with(cx, |this, _| this.abs_path());
2444                let new_abs_path = if is_root_entry {
2445                    root_path
2446                        .parent()
2447                        .unwrap()
2448                        .join(new_path.path.as_std_path())
2449                } else {
2450                    root_path.join(&new_path.path.as_std_path())
2451                };
2452                (root_path.join(old_path.as_std_path()), new_abs_path)
2453            };
2454            let transaction = LspStore::will_rename_entry(
2455                lsp_store.clone(),
2456                worktree_id,
2457                &old_abs_path,
2458                &new_abs_path,
2459                is_dir,
2460                cx.clone(),
2461            )
2462            .await;
2463
2464            let entry = worktree_store
2465                .update(cx, |worktree_store, cx| {
2466                    worktree_store.rename_entry(entry_id, new_path.clone(), cx)
2467                })
2468                .await?;
2469
2470            project
2471                .update(cx, |_, cx| {
2472                    cx.emit(Event::EntryRenamed(
2473                        transaction,
2474                        new_path.clone(),
2475                        new_abs_path.clone(),
2476                    ));
2477                })
2478                .ok();
2479
2480            lsp_store
2481                .read_with(cx, |this, _| {
2482                    this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
2483                })
2484                .ok();
2485            Ok(entry)
2486        })
2487    }
2488
2489    #[inline]
2490    pub fn delete_file(
2491        &mut self,
2492        path: ProjectPath,
2493        trash: bool,
2494        cx: &mut Context<Self>,
2495    ) -> Option<Task<Result<()>>> {
2496        let entry = self.entry_for_path(&path, cx)?;
2497        self.delete_entry(entry.id, trash, cx)
2498    }
2499
2500    #[inline]
2501    pub fn delete_entry(
2502        &mut self,
2503        entry_id: ProjectEntryId,
2504        trash: bool,
2505        cx: &mut Context<Self>,
2506    ) -> Option<Task<Result<()>>> {
2507        let worktree = self.worktree_for_entry(entry_id, cx)?;
2508        cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
2509        worktree.update(cx, |worktree, cx| {
2510            worktree.delete_entry(entry_id, trash, cx)
2511        })
2512    }
2513
2514    #[inline]
2515    pub fn expand_entry(
2516        &mut self,
2517        worktree_id: WorktreeId,
2518        entry_id: ProjectEntryId,
2519        cx: &mut Context<Self>,
2520    ) -> Option<Task<Result<()>>> {
2521        let worktree = self.worktree_for_id(worktree_id, cx)?;
2522        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
2523    }
2524
2525    pub fn expand_all_for_entry(
2526        &mut self,
2527        worktree_id: WorktreeId,
2528        entry_id: ProjectEntryId,
2529        cx: &mut Context<Self>,
2530    ) -> Option<Task<Result<()>>> {
2531        let worktree = self.worktree_for_id(worktree_id, cx)?;
2532        let task = worktree.update(cx, |worktree, cx| {
2533            worktree.expand_all_for_entry(entry_id, cx)
2534        });
2535        Some(cx.spawn(async move |this, cx| {
2536            task.context("no task")?.await?;
2537            this.update(cx, |_, cx| {
2538                cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
2539            })?;
2540            Ok(())
2541        }))
2542    }
2543
2544    pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2545        anyhow::ensure!(
2546            matches!(self.client_state, ProjectClientState::Local),
2547            "project was already shared"
2548        );
2549
2550        self.client_subscriptions.extend([
2551            self.collab_client
2552                .subscribe_to_entity(project_id)?
2553                .set_entity(&cx.entity(), &cx.to_async()),
2554            self.collab_client
2555                .subscribe_to_entity(project_id)?
2556                .set_entity(&self.worktree_store, &cx.to_async()),
2557            self.collab_client
2558                .subscribe_to_entity(project_id)?
2559                .set_entity(&self.buffer_store, &cx.to_async()),
2560            self.collab_client
2561                .subscribe_to_entity(project_id)?
2562                .set_entity(&self.lsp_store, &cx.to_async()),
2563            self.collab_client
2564                .subscribe_to_entity(project_id)?
2565                .set_entity(&self.settings_observer, &cx.to_async()),
2566            self.collab_client
2567                .subscribe_to_entity(project_id)?
2568                .set_entity(&self.dap_store, &cx.to_async()),
2569            self.collab_client
2570                .subscribe_to_entity(project_id)?
2571                .set_entity(&self.breakpoint_store, &cx.to_async()),
2572            self.collab_client
2573                .subscribe_to_entity(project_id)?
2574                .set_entity(&self.git_store, &cx.to_async()),
2575        ]);
2576
2577        self.buffer_store.update(cx, |buffer_store, cx| {
2578            buffer_store.shared(project_id, self.collab_client.clone().into(), cx)
2579        });
2580        self.worktree_store.update(cx, |worktree_store, cx| {
2581            worktree_store.shared(project_id, self.collab_client.clone().into(), cx);
2582        });
2583        self.lsp_store.update(cx, |lsp_store, cx| {
2584            lsp_store.shared(project_id, self.collab_client.clone().into(), cx)
2585        });
2586        self.breakpoint_store.update(cx, |breakpoint_store, _| {
2587            breakpoint_store.shared(project_id, self.collab_client.clone().into())
2588        });
2589        self.dap_store.update(cx, |dap_store, cx| {
2590            dap_store.shared(project_id, self.collab_client.clone().into(), cx);
2591        });
2592        self.task_store.update(cx, |task_store, cx| {
2593            task_store.shared(project_id, self.collab_client.clone().into(), cx);
2594        });
2595        self.settings_observer.update(cx, |settings_observer, cx| {
2596            settings_observer.shared(project_id, self.collab_client.clone().into(), cx)
2597        });
2598        self.git_store.update(cx, |git_store, cx| {
2599            git_store.shared(project_id, self.collab_client.clone().into(), cx)
2600        });
2601
2602        self.client_state = ProjectClientState::Shared {
2603            remote_id: project_id,
2604        };
2605
2606        cx.emit(Event::RemoteIdChanged(Some(project_id)));
2607        Ok(())
2608    }
2609
2610    pub fn reshared(
2611        &mut self,
2612        message: proto::ResharedProject,
2613        cx: &mut Context<Self>,
2614    ) -> Result<()> {
2615        self.buffer_store
2616            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2617        self.set_collaborators_from_proto(message.collaborators, cx)?;
2618
2619        self.worktree_store.update(cx, |worktree_store, cx| {
2620            worktree_store.send_project_updates(cx);
2621        });
2622        if let Some(remote_id) = self.remote_id() {
2623            self.git_store.update(cx, |git_store, cx| {
2624                git_store.shared(remote_id, self.collab_client.clone().into(), cx)
2625            });
2626        }
2627        cx.emit(Event::Reshared);
2628        Ok(())
2629    }
2630
2631    pub fn rejoined(
2632        &mut self,
2633        message: proto::RejoinedProject,
2634        message_id: u32,
2635        cx: &mut Context<Self>,
2636    ) -> Result<()> {
2637        cx.update_global::<SettingsStore, _>(|store, cx| {
2638            for worktree_metadata in &message.worktrees {
2639                store
2640                    .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
2641                    .log_err();
2642            }
2643        });
2644
2645        self.join_project_response_message_id = message_id;
2646        self.set_worktrees_from_proto(message.worktrees, cx)?;
2647        self.set_collaborators_from_proto(message.collaborators, cx)?;
2648
2649        let project = cx.weak_entity();
2650        self.lsp_store.update(cx, |lsp_store, cx| {
2651            lsp_store.set_language_server_statuses_from_proto(
2652                project,
2653                message.language_servers,
2654                message.language_server_capabilities,
2655                cx,
2656            )
2657        });
2658        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2659            .unwrap();
2660        cx.emit(Event::Rejoined);
2661        Ok(())
2662    }
2663
2664    #[inline]
2665    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2666        self.unshare_internal(cx)?;
2667        cx.emit(Event::RemoteIdChanged(None));
2668        Ok(())
2669    }
2670
2671    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2672        anyhow::ensure!(
2673            !self.is_via_collab(),
2674            "attempted to unshare a remote project"
2675        );
2676
2677        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2678            self.client_state = ProjectClientState::Local;
2679            self.collaborators.clear();
2680            self.client_subscriptions.clear();
2681            self.worktree_store.update(cx, |store, cx| {
2682                store.unshared(cx);
2683            });
2684            self.buffer_store.update(cx, |buffer_store, cx| {
2685                buffer_store.forget_shared_buffers();
2686                buffer_store.unshared(cx)
2687            });
2688            self.task_store.update(cx, |task_store, cx| {
2689                task_store.unshared(cx);
2690            });
2691            self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2692                breakpoint_store.unshared(cx);
2693            });
2694            self.dap_store.update(cx, |dap_store, cx| {
2695                dap_store.unshared(cx);
2696            });
2697            self.settings_observer.update(cx, |settings_observer, cx| {
2698                settings_observer.unshared(cx);
2699            });
2700            self.git_store.update(cx, |git_store, cx| {
2701                git_store.unshared(cx);
2702            });
2703
2704            self.collab_client
2705                .send(proto::UnshareProject {
2706                    project_id: remote_id,
2707                })
2708                .ok();
2709            Ok(())
2710        } else {
2711            anyhow::bail!("attempted to unshare an unshared project");
2712        }
2713    }
2714
2715    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2716        if self.is_disconnected(cx) {
2717            return;
2718        }
2719        self.disconnected_from_host_internal(cx);
2720        cx.emit(Event::DisconnectedFromHost);
2721    }
2722
2723    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2724        let new_capability =
2725            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2726                Capability::ReadWrite
2727            } else {
2728                Capability::ReadOnly
2729            };
2730        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
2731            if *capability == new_capability {
2732                return;
2733            }
2734
2735            *capability = new_capability;
2736            for buffer in self.opened_buffers(cx) {
2737                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2738            }
2739        }
2740    }
2741
2742    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2743        if let ProjectClientState::Remote {
2744            sharing_has_stopped,
2745            ..
2746        } = &mut self.client_state
2747        {
2748            *sharing_has_stopped = true;
2749            self.client_subscriptions.clear();
2750            self.collaborators.clear();
2751            self.worktree_store.update(cx, |store, cx| {
2752                store.disconnected_from_host(cx);
2753            });
2754            self.buffer_store.update(cx, |buffer_store, cx| {
2755                buffer_store.disconnected_from_host(cx)
2756            });
2757            self.lsp_store
2758                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2759        }
2760    }
2761
2762    #[inline]
2763    pub fn close(&mut self, cx: &mut Context<Self>) {
2764        cx.emit(Event::Closed);
2765    }
2766
2767    #[inline]
2768    pub fn is_disconnected(&self, cx: &App) -> bool {
2769        match &self.client_state {
2770            ProjectClientState::Remote {
2771                sharing_has_stopped,
2772                ..
2773            } => *sharing_has_stopped,
2774            ProjectClientState::Local if self.is_via_remote_server() => {
2775                self.remote_client_is_disconnected(cx)
2776            }
2777            _ => false,
2778        }
2779    }
2780
2781    #[inline]
2782    fn remote_client_is_disconnected(&self, cx: &App) -> bool {
2783        self.remote_client
2784            .as_ref()
2785            .map(|remote| remote.read(cx).is_disconnected())
2786            .unwrap_or(false)
2787    }
2788
2789    #[inline]
2790    pub fn capability(&self) -> Capability {
2791        match &self.client_state {
2792            ProjectClientState::Remote { capability, .. } => *capability,
2793            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2794        }
2795    }
2796
2797    #[inline]
2798    pub fn is_read_only(&self, cx: &App) -> bool {
2799        self.is_disconnected(cx) || !self.capability().editable()
2800    }
2801
2802    #[inline]
2803    pub fn is_local(&self) -> bool {
2804        match &self.client_state {
2805            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2806                self.remote_client.is_none()
2807            }
2808            ProjectClientState::Remote { .. } => false,
2809        }
2810    }
2811
2812    /// Whether this project is a remote server (not counting collab).
2813    #[inline]
2814    pub fn is_via_remote_server(&self) -> bool {
2815        match &self.client_state {
2816            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2817                self.remote_client.is_some()
2818            }
2819            ProjectClientState::Remote { .. } => false,
2820        }
2821    }
2822
2823    /// Whether this project is from collab (not counting remote servers).
2824    #[inline]
2825    pub fn is_via_collab(&self) -> bool {
2826        match &self.client_state {
2827            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2828            ProjectClientState::Remote { .. } => true,
2829        }
2830    }
2831
2832    /// `!self.is_local()`
2833    #[inline]
2834    pub fn is_remote(&self) -> bool {
2835        debug_assert_eq!(
2836            !self.is_local(),
2837            self.is_via_collab() || self.is_via_remote_server()
2838        );
2839        !self.is_local()
2840    }
2841
2842    #[inline]
2843    pub fn is_via_wsl_with_host_interop(&self, cx: &App) -> bool {
2844        match &self.client_state {
2845            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2846                matches!(
2847                    &self.remote_client, Some(remote_client)
2848                    if remote_client.read(cx).has_wsl_interop()
2849                )
2850            }
2851            _ => false,
2852        }
2853    }
2854
2855    pub fn disable_worktree_scanner(&mut self, cx: &mut Context<Self>) {
2856        self.worktree_store.update(cx, |worktree_store, _cx| {
2857            worktree_store.disable_scanner();
2858        });
2859    }
2860
2861    #[inline]
2862    pub fn create_buffer(
2863        &mut self,
2864        language: Option<Arc<Language>>,
2865        project_searchable: bool,
2866        cx: &mut Context<Self>,
2867    ) -> Task<Result<Entity<Buffer>>> {
2868        self.buffer_store.update(cx, |buffer_store, cx| {
2869            buffer_store.create_buffer(language, project_searchable, cx)
2870        })
2871    }
2872
2873    #[inline]
2874    pub fn create_local_buffer(
2875        &mut self,
2876        text: &str,
2877        language: Option<Arc<Language>>,
2878        project_searchable: bool,
2879        cx: &mut Context<Self>,
2880    ) -> Entity<Buffer> {
2881        if self.is_remote() {
2882            panic!("called create_local_buffer on a remote project")
2883        }
2884        self.buffer_store.update(cx, |buffer_store, cx| {
2885            buffer_store.create_local_buffer(text, language, project_searchable, cx)
2886        })
2887    }
2888
2889    pub fn open_path(
2890        &mut self,
2891        path: ProjectPath,
2892        cx: &mut Context<Self>,
2893    ) -> Task<Result<(Option<ProjectEntryId>, Entity<Buffer>)>> {
2894        let task = self.open_buffer(path, cx);
2895        cx.spawn(async move |_project, cx| {
2896            let buffer = task.await?;
2897            let project_entry_id = buffer.read_with(cx, |buffer, _cx| {
2898                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id())
2899            });
2900
2901            Ok((project_entry_id, buffer))
2902        })
2903    }
2904
2905    pub fn open_local_buffer(
2906        &mut self,
2907        abs_path: impl AsRef<Path>,
2908        cx: &mut Context<Self>,
2909    ) -> Task<Result<Entity<Buffer>>> {
2910        let worktree_task = self.find_or_create_worktree(abs_path.as_ref(), false, cx);
2911        cx.spawn(async move |this, cx| {
2912            let (worktree, relative_path) = worktree_task.await?;
2913            this.update(cx, |this, cx| {
2914                this.open_buffer((worktree.read(cx).id(), relative_path), cx)
2915            })?
2916            .await
2917        })
2918    }
2919
2920    #[cfg(feature = "test-support")]
2921    pub fn open_local_buffer_with_lsp(
2922        &mut self,
2923        abs_path: impl AsRef<Path>,
2924        cx: &mut Context<Self>,
2925    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2926        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2927            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
2928        } else {
2929            Task::ready(Err(anyhow!("no such path")))
2930        }
2931    }
2932
2933    pub fn download_file(
2934        &mut self,
2935        worktree_id: WorktreeId,
2936        path: Arc<RelPath>,
2937        destination_path: PathBuf,
2938        cx: &mut Context<Self>,
2939    ) -> Task<Result<()>> {
2940        log::debug!(
2941            "download_file called: worktree_id={:?}, path={:?}, destination={:?}",
2942            worktree_id,
2943            path,
2944            destination_path
2945        );
2946
2947        let Some(remote_client) = &self.remote_client else {
2948            log::error!("download_file: not a remote project");
2949            return Task::ready(Err(anyhow!("not a remote project")));
2950        };
2951
2952        let proto_client = remote_client.read(cx).proto_client();
2953        // For SSH remote projects, use REMOTE_SERVER_PROJECT_ID instead of remote_id()
2954        // because SSH projects have client_state: Local but still need to communicate with remote server
2955        let project_id = self.remote_id().unwrap_or(REMOTE_SERVER_PROJECT_ID);
2956        let downloading_files = self.downloading_files.clone();
2957        let path_str = path.to_proto();
2958
2959        static NEXT_FILE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
2960        let file_id = NEXT_FILE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2961
2962        // Register BEFORE sending request to avoid race condition
2963        let key = (worktree_id, path_str.clone());
2964        log::debug!(
2965            "download_file: pre-registering download with key={:?}, file_id={}",
2966            key,
2967            file_id
2968        );
2969        downloading_files.lock().insert(
2970            key,
2971            DownloadingFile {
2972                destination_path: destination_path,
2973                chunks: Vec::new(),
2974                total_size: 0,
2975                file_id: Some(file_id),
2976            },
2977        );
2978        log::debug!(
2979            "download_file: sending DownloadFileByPath request, path_str={}",
2980            path_str
2981        );
2982
2983        cx.spawn(async move |_this, _cx| {
2984            log::debug!("download_file: sending request with file_id={}...", file_id);
2985            let response = proto_client
2986                .request(proto::DownloadFileByPath {
2987                    project_id,
2988                    worktree_id: worktree_id.to_proto(),
2989                    path: path_str.clone(),
2990                    file_id,
2991                })
2992                .await?;
2993
2994            log::debug!("download_file: got response, file_id={}", response.file_id);
2995            // The file_id is set from the State message, we just confirm the request succeeded
2996            Ok(())
2997        })
2998    }
2999
3000    #[ztracing::instrument(skip_all)]
3001    pub fn open_buffer(
3002        &mut self,
3003        path: impl Into<ProjectPath>,
3004        cx: &mut App,
3005    ) -> Task<Result<Entity<Buffer>>> {
3006        if self.is_disconnected(cx) {
3007            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3008        }
3009
3010        self.buffer_store.update(cx, |buffer_store, cx| {
3011            buffer_store.open_buffer(path.into(), cx)
3012        })
3013    }
3014
3015    #[cfg(feature = "test-support")]
3016    pub fn open_buffer_with_lsp(
3017        &mut self,
3018        path: impl Into<ProjectPath>,
3019        cx: &mut Context<Self>,
3020    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
3021        let buffer = self.open_buffer(path, cx);
3022        cx.spawn(async move |this, cx| {
3023            let buffer = buffer.await?;
3024            let handle = this.update(cx, |project, cx| {
3025                project.register_buffer_with_language_servers(&buffer, cx)
3026            })?;
3027            Ok((buffer, handle))
3028        })
3029    }
3030
3031    pub fn register_buffer_with_language_servers(
3032        &self,
3033        buffer: &Entity<Buffer>,
3034        cx: &mut App,
3035    ) -> OpenLspBufferHandle {
3036        self.lsp_store.update(cx, |lsp_store, cx| {
3037            lsp_store.register_buffer_with_language_servers(buffer, HashSet::default(), false, cx)
3038        })
3039    }
3040
3041    pub fn open_unstaged_diff(
3042        &mut self,
3043        buffer: Entity<Buffer>,
3044        cx: &mut Context<Self>,
3045    ) -> Task<Result<Entity<BufferDiff>>> {
3046        if self.is_disconnected(cx) {
3047            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3048        }
3049        self.git_store
3050            .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
3051    }
3052
3053    #[ztracing::instrument(skip_all)]
3054    pub fn open_uncommitted_diff(
3055        &mut self,
3056        buffer: Entity<Buffer>,
3057        cx: &mut Context<Self>,
3058    ) -> Task<Result<Entity<BufferDiff>>> {
3059        if self.is_disconnected(cx) {
3060            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3061        }
3062        self.git_store.update(cx, |git_store, cx| {
3063            git_store.open_uncommitted_diff(buffer, cx)
3064        })
3065    }
3066
3067    pub fn open_buffer_by_id(
3068        &mut self,
3069        id: BufferId,
3070        cx: &mut Context<Self>,
3071    ) -> Task<Result<Entity<Buffer>>> {
3072        if let Some(buffer) = self.buffer_for_id(id, cx) {
3073            Task::ready(Ok(buffer))
3074        } else if self.is_local() || self.is_via_remote_server() {
3075            Task::ready(Err(anyhow!("buffer {id} does not exist")))
3076        } else if let Some(project_id) = self.remote_id() {
3077            let request = self.collab_client.request(proto::OpenBufferById {
3078                project_id,
3079                id: id.into(),
3080            });
3081            cx.spawn(async move |project, cx| {
3082                let buffer_id = BufferId::new(request.await?.buffer_id)?;
3083                project
3084                    .update(cx, |project, cx| {
3085                        project.buffer_store.update(cx, |buffer_store, cx| {
3086                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
3087                        })
3088                    })?
3089                    .await
3090            })
3091        } else {
3092            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
3093        }
3094    }
3095
3096    pub fn save_buffers(
3097        &self,
3098        buffers: HashSet<Entity<Buffer>>,
3099        cx: &mut Context<Self>,
3100    ) -> Task<Result<()>> {
3101        cx.spawn(async move |this, cx| {
3102            let save_tasks = buffers.into_iter().filter_map(|buffer| {
3103                this.update(cx, |this, cx| this.save_buffer(buffer, cx))
3104                    .ok()
3105            });
3106            try_join_all(save_tasks).await?;
3107            Ok(())
3108        })
3109    }
3110
3111    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
3112        self.buffer_store
3113            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
3114    }
3115
3116    pub fn save_buffer_as(
3117        &mut self,
3118        buffer: Entity<Buffer>,
3119        path: ProjectPath,
3120        cx: &mut Context<Self>,
3121    ) -> Task<Result<()>> {
3122        self.buffer_store.update(cx, |buffer_store, cx| {
3123            buffer_store.save_buffer_as(buffer.clone(), path, cx)
3124        })
3125    }
3126
3127    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
3128        self.buffer_store.read(cx).get_by_path(path)
3129    }
3130
3131    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3132        {
3133            let mut remotely_created_models = self.remotely_created_models.lock();
3134            if remotely_created_models.retain_count > 0 {
3135                remotely_created_models.buffers.push(buffer.clone())
3136            }
3137        }
3138
3139        self.request_buffer_diff_recalculation(buffer, cx);
3140
3141        cx.subscribe(buffer, |this, buffer, event, cx| {
3142            this.on_buffer_event(buffer, event, cx);
3143        })
3144        .detach();
3145
3146        Ok(())
3147    }
3148
3149    pub fn open_image(
3150        &mut self,
3151        path: impl Into<ProjectPath>,
3152        cx: &mut Context<Self>,
3153    ) -> Task<Result<Entity<ImageItem>>> {
3154        if self.is_disconnected(cx) {
3155            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3156        }
3157
3158        let open_image_task = self.image_store.update(cx, |image_store, cx| {
3159            image_store.open_image(path.into(), cx)
3160        });
3161
3162        let weak_project = cx.entity().downgrade();
3163        cx.spawn(async move |_, cx| {
3164            let image_item = open_image_task.await?;
3165
3166            // Check if metadata already exists (e.g., for remote images)
3167            let needs_metadata =
3168                cx.read_entity(&image_item, |item, _| item.image_metadata.is_none());
3169
3170            if needs_metadata {
3171                let project = weak_project.upgrade().context("Project dropped")?;
3172                let metadata =
3173                    ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
3174                image_item.update(cx, |image_item, cx| {
3175                    image_item.image_metadata = Some(metadata);
3176                    cx.emit(ImageItemEvent::MetadataUpdated);
3177                });
3178            }
3179
3180            Ok(image_item)
3181        })
3182    }
3183
3184    async fn send_buffer_ordered_messages(
3185        project: WeakEntity<Self>,
3186        rx: UnboundedReceiver<BufferOrderedMessage>,
3187        cx: &mut AsyncApp,
3188    ) -> Result<()> {
3189        const MAX_BATCH_SIZE: usize = 128;
3190
3191        let mut operations_by_buffer_id = HashMap::default();
3192        async fn flush_operations(
3193            this: &WeakEntity<Project>,
3194            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
3195            needs_resync_with_host: &mut bool,
3196            is_local: bool,
3197            cx: &mut AsyncApp,
3198        ) -> Result<()> {
3199            for (buffer_id, operations) in operations_by_buffer_id.drain() {
3200                let request = this.read_with(cx, |this, _| {
3201                    let project_id = this.remote_id()?;
3202                    Some(this.collab_client.request(proto::UpdateBuffer {
3203                        buffer_id: buffer_id.into(),
3204                        project_id,
3205                        operations,
3206                    }))
3207                })?;
3208                if let Some(request) = request
3209                    && request.await.is_err()
3210                    && !is_local
3211                {
3212                    *needs_resync_with_host = true;
3213                    break;
3214                }
3215            }
3216            Ok(())
3217        }
3218
3219        let mut needs_resync_with_host = false;
3220        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
3221
3222        while let Some(changes) = changes.next().await {
3223            let is_local = project.read_with(cx, |this, _| this.is_local())?;
3224
3225            for change in changes {
3226                match change {
3227                    BufferOrderedMessage::Operation {
3228                        buffer_id,
3229                        operation,
3230                    } => {
3231                        if needs_resync_with_host {
3232                            continue;
3233                        }
3234
3235                        operations_by_buffer_id
3236                            .entry(buffer_id)
3237                            .or_insert(Vec::new())
3238                            .push(operation);
3239                    }
3240
3241                    BufferOrderedMessage::Resync => {
3242                        operations_by_buffer_id.clear();
3243                        if project
3244                            .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
3245                            .await
3246                            .is_ok()
3247                        {
3248                            needs_resync_with_host = false;
3249                        }
3250                    }
3251
3252                    BufferOrderedMessage::LanguageServerUpdate {
3253                        language_server_id,
3254                        message,
3255                        name,
3256                    } => {
3257                        flush_operations(
3258                            &project,
3259                            &mut operations_by_buffer_id,
3260                            &mut needs_resync_with_host,
3261                            is_local,
3262                            cx,
3263                        )
3264                        .await?;
3265
3266                        project.read_with(cx, |project, _| {
3267                            if let Some(project_id) = project.remote_id() {
3268                                project
3269                                    .collab_client
3270                                    .send(proto::UpdateLanguageServer {
3271                                        project_id,
3272                                        server_name: name.map(|name| String::from(name.0)),
3273                                        language_server_id: language_server_id.to_proto(),
3274                                        variant: Some(message),
3275                                    })
3276                                    .log_err();
3277                            }
3278                        })?;
3279                    }
3280                }
3281            }
3282
3283            flush_operations(
3284                &project,
3285                &mut operations_by_buffer_id,
3286                &mut needs_resync_with_host,
3287                is_local,
3288                cx,
3289            )
3290            .await?;
3291        }
3292
3293        Ok(())
3294    }
3295
3296    fn on_buffer_store_event(
3297        &mut self,
3298        _: Entity<BufferStore>,
3299        event: &BufferStoreEvent,
3300        cx: &mut Context<Self>,
3301    ) {
3302        match event {
3303            BufferStoreEvent::BufferAdded(buffer) => {
3304                self.register_buffer(buffer, cx).log_err();
3305            }
3306            BufferStoreEvent::BufferDropped(buffer_id) => {
3307                if let Some(ref remote_client) = self.remote_client {
3308                    remote_client
3309                        .read(cx)
3310                        .proto_client()
3311                        .send(proto::CloseBuffer {
3312                            project_id: 0,
3313                            buffer_id: buffer_id.to_proto(),
3314                        })
3315                        .log_err();
3316                }
3317            }
3318            _ => {}
3319        }
3320    }
3321
3322    fn on_image_store_event(
3323        &mut self,
3324        _: Entity<ImageStore>,
3325        event: &ImageStoreEvent,
3326        cx: &mut Context<Self>,
3327    ) {
3328        match event {
3329            ImageStoreEvent::ImageAdded(image) => {
3330                cx.subscribe(image, |this, image, event, cx| {
3331                    this.on_image_event(image, event, cx);
3332                })
3333                .detach();
3334            }
3335        }
3336    }
3337
3338    fn on_dap_store_event(
3339        &mut self,
3340        _: Entity<DapStore>,
3341        event: &DapStoreEvent,
3342        cx: &mut Context<Self>,
3343    ) {
3344        if let DapStoreEvent::Notification(message) = event {
3345            cx.emit(Event::Toast {
3346                notification_id: "dap".into(),
3347                message: message.clone(),
3348                link: None,
3349            });
3350        }
3351    }
3352
3353    fn on_lsp_store_event(
3354        &mut self,
3355        _: Entity<LspStore>,
3356        event: &LspStoreEvent,
3357        cx: &mut Context<Self>,
3358    ) {
3359        match event {
3360            LspStoreEvent::DiagnosticsUpdated { server_id, paths } => {
3361                cx.emit(Event::DiagnosticsUpdated {
3362                    paths: paths.clone(),
3363                    language_server_id: *server_id,
3364                })
3365            }
3366            LspStoreEvent::LanguageServerAdded(server_id, name, worktree_id) => cx.emit(
3367                Event::LanguageServerAdded(*server_id, name.clone(), *worktree_id),
3368            ),
3369            LspStoreEvent::LanguageServerRemoved(server_id) => {
3370                cx.emit(Event::LanguageServerRemoved(*server_id))
3371            }
3372            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
3373                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
3374            ),
3375            LspStoreEvent::LanguageDetected {
3376                buffer,
3377                new_language,
3378            } => {
3379                let Some(_) = new_language else {
3380                    cx.emit(Event::LanguageNotFound(buffer.clone()));
3381                    return;
3382                };
3383            }
3384            LspStoreEvent::RefreshInlayHints {
3385                server_id,
3386                request_id,
3387            } => cx.emit(Event::RefreshInlayHints {
3388                server_id: *server_id,
3389                request_id: *request_id,
3390            }),
3391            LspStoreEvent::RefreshSemanticTokens {
3392                server_id,
3393                request_id,
3394            } => cx.emit(Event::RefreshSemanticTokens {
3395                server_id: *server_id,
3396                request_id: *request_id,
3397            }),
3398            LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
3399            LspStoreEvent::LanguageServerPrompt(prompt) => {
3400                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
3401            }
3402            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
3403                cx.emit(Event::DiskBasedDiagnosticsStarted {
3404                    language_server_id: *language_server_id,
3405                });
3406            }
3407            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
3408                cx.emit(Event::DiskBasedDiagnosticsFinished {
3409                    language_server_id: *language_server_id,
3410                });
3411            }
3412            LspStoreEvent::LanguageServerUpdate {
3413                language_server_id,
3414                name,
3415                message,
3416            } => {
3417                if self.is_local() {
3418                    self.enqueue_buffer_ordered_message(
3419                        BufferOrderedMessage::LanguageServerUpdate {
3420                            language_server_id: *language_server_id,
3421                            message: message.clone(),
3422                            name: name.clone(),
3423                        },
3424                    )
3425                    .ok();
3426                }
3427
3428                match message {
3429                    proto::update_language_server::Variant::MetadataUpdated(update) => {
3430                        self.lsp_store.update(cx, |lsp_store, _| {
3431                            if let Some(capabilities) = update
3432                                .capabilities
3433                                .as_ref()
3434                                .and_then(|capabilities| serde_json::from_str(capabilities).ok())
3435                            {
3436                                lsp_store
3437                                    .lsp_server_capabilities
3438                                    .insert(*language_server_id, capabilities);
3439                            }
3440
3441                            if let Some(language_server_status) = lsp_store
3442                                .language_server_statuses
3443                                .get_mut(language_server_id)
3444                            {
3445                                if let Some(binary) = &update.binary {
3446                                    language_server_status.binary = Some(LanguageServerBinary {
3447                                        path: PathBuf::from(&binary.path),
3448                                        arguments: binary
3449                                            .arguments
3450                                            .iter()
3451                                            .map(OsString::from)
3452                                            .collect(),
3453                                        env: None,
3454                                    });
3455                                }
3456
3457                                language_server_status.configuration = update
3458                                    .configuration
3459                                    .as_ref()
3460                                    .and_then(|config_str| serde_json::from_str(config_str).ok());
3461
3462                                language_server_status.workspace_folders = update
3463                                    .workspace_folders
3464                                    .iter()
3465                                    .filter_map(|uri_str| lsp::Uri::from_str(uri_str).ok())
3466                                    .collect();
3467                            }
3468                        });
3469                    }
3470                    proto::update_language_server::Variant::RegisteredForBuffer(update) => {
3471                        if let Some(buffer_id) = BufferId::new(update.buffer_id).ok() {
3472                            cx.emit(Event::LanguageServerBufferRegistered {
3473                                buffer_id,
3474                                server_id: *language_server_id,
3475                                buffer_abs_path: PathBuf::from(&update.buffer_abs_path),
3476                                name: name.clone(),
3477                            });
3478                        }
3479                    }
3480                    _ => (),
3481                }
3482            }
3483            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
3484                notification_id: "lsp".into(),
3485                message: message.clone(),
3486                link: None,
3487            }),
3488            LspStoreEvent::SnippetEdit {
3489                buffer_id,
3490                edits,
3491                most_recent_edit,
3492            } => {
3493                if most_recent_edit.replica_id == self.replica_id() {
3494                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
3495                }
3496            }
3497            LspStoreEvent::WorkspaceEditApplied(transaction) => {
3498                cx.emit(Event::WorkspaceEditApplied(transaction.clone()))
3499            }
3500        }
3501    }
3502
3503    fn on_remote_client_event(
3504        &mut self,
3505        _: Entity<RemoteClient>,
3506        event: &remote::RemoteClientEvent,
3507        cx: &mut Context<Self>,
3508    ) {
3509        match event {
3510            &remote::RemoteClientEvent::Disconnected { server_not_running } => {
3511                self.worktree_store.update(cx, |store, cx| {
3512                    store.disconnected_from_host(cx);
3513                });
3514                self.buffer_store.update(cx, |buffer_store, cx| {
3515                    buffer_store.disconnected_from_host(cx)
3516                });
3517                self.lsp_store.update(cx, |lsp_store, _cx| {
3518                    lsp_store.disconnected_from_ssh_remote()
3519                });
3520                cx.emit(Event::DisconnectedFromRemote { server_not_running });
3521            }
3522        }
3523    }
3524
3525    fn on_settings_observer_event(
3526        &mut self,
3527        _: Entity<SettingsObserver>,
3528        event: &SettingsObserverEvent,
3529        cx: &mut Context<Self>,
3530    ) {
3531        match event {
3532            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
3533                Err(InvalidSettingsError::LocalSettings { message, path }) => {
3534                    let message = format!("Failed to set local settings in {path:?}:\n{message}");
3535                    cx.emit(Event::Toast {
3536                        notification_id: format!("local-settings-{path:?}").into(),
3537                        link: None,
3538                        message,
3539                    });
3540                }
3541                Ok(path) => cx.emit(Event::HideToast {
3542                    notification_id: format!("local-settings-{path:?}").into(),
3543                }),
3544                Err(_) => {}
3545            },
3546            SettingsObserverEvent::LocalTasksUpdated(result) => match result {
3547                Err(InvalidSettingsError::Tasks { message, path }) => {
3548                    let message = format!("Failed to set local tasks in {path:?}:\n{message}");
3549                    cx.emit(Event::Toast {
3550                        notification_id: format!("local-tasks-{path:?}").into(),
3551                        link: Some(ToastLink {
3552                            label: "Open Tasks Documentation",
3553                            url: "https://zed.dev/docs/tasks",
3554                        }),
3555                        message,
3556                    });
3557                }
3558                Ok(path) => cx.emit(Event::HideToast {
3559                    notification_id: format!("local-tasks-{path:?}").into(),
3560                }),
3561                Err(_) => {}
3562            },
3563            SettingsObserverEvent::LocalDebugScenariosUpdated(result) => match result {
3564                Err(InvalidSettingsError::Debug { message, path }) => {
3565                    let message =
3566                        format!("Failed to set local debug scenarios in {path:?}:\n{message}");
3567                    cx.emit(Event::Toast {
3568                        notification_id: format!("local-debug-scenarios-{path:?}").into(),
3569                        link: None,
3570                        message,
3571                    });
3572                }
3573                Ok(path) => cx.emit(Event::HideToast {
3574                    notification_id: format!("local-debug-scenarios-{path:?}").into(),
3575                }),
3576                Err(_) => {}
3577            },
3578        }
3579    }
3580
3581    fn on_worktree_store_event(
3582        &mut self,
3583        _: Entity<WorktreeStore>,
3584        event: &WorktreeStoreEvent,
3585        cx: &mut Context<Self>,
3586    ) {
3587        match event {
3588            WorktreeStoreEvent::WorktreeAdded(worktree) => {
3589                self.on_worktree_added(worktree, cx);
3590                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
3591            }
3592            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
3593                cx.emit(Event::WorktreeRemoved(*id));
3594            }
3595            WorktreeStoreEvent::WorktreeReleased(_, id) => {
3596                self.on_worktree_released(*id, cx);
3597            }
3598            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
3599            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
3600            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
3601                self.client()
3602                    .telemetry()
3603                    .report_discovered_project_type_events(*worktree_id, changes);
3604                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
3605            }
3606            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
3607                cx.emit(Event::DeletedEntry(*worktree_id, *id))
3608            }
3609            // Listen to the GitStore instead.
3610            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
3611        }
3612    }
3613
3614    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
3615        let mut remotely_created_models = self.remotely_created_models.lock();
3616        if remotely_created_models.retain_count > 0 {
3617            remotely_created_models.worktrees.push(worktree.clone())
3618        }
3619    }
3620
3621    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3622        if let Some(remote) = &self.remote_client {
3623            remote
3624                .read(cx)
3625                .proto_client()
3626                .send(proto::RemoveWorktree {
3627                    worktree_id: id_to_remove.to_proto(),
3628                })
3629                .log_err();
3630        }
3631    }
3632
3633    fn on_buffer_event(
3634        &mut self,
3635        buffer: Entity<Buffer>,
3636        event: &BufferEvent,
3637        cx: &mut Context<Self>,
3638    ) -> Option<()> {
3639        if matches!(event, BufferEvent::Edited | BufferEvent::Reloaded) {
3640            self.request_buffer_diff_recalculation(&buffer, cx);
3641        }
3642
3643        if matches!(event, BufferEvent::Edited) {
3644            cx.emit(Event::BufferEdited);
3645        }
3646
3647        let buffer_id = buffer.read(cx).remote_id();
3648        match event {
3649            BufferEvent::ReloadNeeded => {
3650                if !self.is_via_collab() {
3651                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
3652                        .detach_and_log_err(cx);
3653                }
3654            }
3655            BufferEvent::Operation {
3656                operation,
3657                is_local: true,
3658            } => {
3659                let operation = language::proto::serialize_operation(operation);
3660
3661                if let Some(remote) = &self.remote_client {
3662                    remote
3663                        .read(cx)
3664                        .proto_client()
3665                        .send(proto::UpdateBuffer {
3666                            project_id: 0,
3667                            buffer_id: buffer_id.to_proto(),
3668                            operations: vec![operation.clone()],
3669                        })
3670                        .ok();
3671                }
3672
3673                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
3674                    buffer_id,
3675                    operation,
3676                })
3677                .ok();
3678            }
3679
3680            _ => {}
3681        }
3682
3683        None
3684    }
3685
3686    fn on_image_event(
3687        &mut self,
3688        image: Entity<ImageItem>,
3689        event: &ImageItemEvent,
3690        cx: &mut Context<Self>,
3691    ) -> Option<()> {
3692        // TODO: handle image events from remote
3693        if let ImageItemEvent::ReloadNeeded = event
3694            && !self.is_via_collab()
3695        {
3696            self.reload_images([image].into_iter().collect(), cx)
3697                .detach_and_log_err(cx);
3698        }
3699
3700        None
3701    }
3702
3703    fn request_buffer_diff_recalculation(
3704        &mut self,
3705        buffer: &Entity<Buffer>,
3706        cx: &mut Context<Self>,
3707    ) {
3708        self.buffers_needing_diff.insert(buffer.downgrade());
3709        let first_insertion = self.buffers_needing_diff.len() == 1;
3710        let settings = ProjectSettings::get_global(cx);
3711        let delay = settings.git.gutter_debounce;
3712
3713        if delay == 0 {
3714            if first_insertion {
3715                let this = cx.weak_entity();
3716                cx.defer(move |cx| {
3717                    if let Some(this) = this.upgrade() {
3718                        this.update(cx, |this, cx| {
3719                            this.recalculate_buffer_diffs(cx).detach();
3720                        });
3721                    }
3722                });
3723            }
3724            return;
3725        }
3726
3727        const MIN_DELAY: u64 = 50;
3728        let delay = delay.max(MIN_DELAY);
3729        let duration = Duration::from_millis(delay);
3730
3731        self.git_diff_debouncer
3732            .fire_new(duration, cx, move |this, cx| {
3733                this.recalculate_buffer_diffs(cx)
3734            });
3735    }
3736
3737    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
3738        cx.spawn(async move |this, cx| {
3739            loop {
3740                let task = this
3741                    .update(cx, |this, cx| {
3742                        let buffers = this
3743                            .buffers_needing_diff
3744                            .drain()
3745                            .filter_map(|buffer| buffer.upgrade())
3746                            .collect::<Vec<_>>();
3747                        if buffers.is_empty() {
3748                            None
3749                        } else {
3750                            Some(this.git_store.update(cx, |git_store, cx| {
3751                                git_store.recalculate_buffer_diffs(buffers, cx)
3752                            }))
3753                        }
3754                    })
3755                    .ok()
3756                    .flatten();
3757
3758                if let Some(task) = task {
3759                    task.await;
3760                } else {
3761                    break;
3762                }
3763            }
3764        })
3765    }
3766
3767    pub fn set_language_for_buffer(
3768        &mut self,
3769        buffer: &Entity<Buffer>,
3770        new_language: Arc<Language>,
3771        cx: &mut Context<Self>,
3772    ) {
3773        self.lsp_store.update(cx, |lsp_store, cx| {
3774            lsp_store.set_language_for_buffer(buffer, new_language, cx)
3775        })
3776    }
3777
3778    pub fn restart_language_servers_for_buffers(
3779        &mut self,
3780        buffers: Vec<Entity<Buffer>>,
3781        only_restart_servers: HashSet<LanguageServerSelector>,
3782        cx: &mut Context<Self>,
3783    ) {
3784        self.lsp_store.update(cx, |lsp_store, cx| {
3785            lsp_store.restart_language_servers_for_buffers(buffers, only_restart_servers, cx)
3786        })
3787    }
3788
3789    pub fn stop_language_servers_for_buffers(
3790        &mut self,
3791        buffers: Vec<Entity<Buffer>>,
3792        also_restart_servers: HashSet<LanguageServerSelector>,
3793        cx: &mut Context<Self>,
3794    ) {
3795        self.lsp_store
3796            .update(cx, |lsp_store, cx| {
3797                lsp_store.stop_language_servers_for_buffers(buffers, also_restart_servers, cx)
3798            })
3799            .detach_and_log_err(cx);
3800    }
3801
3802    pub fn cancel_language_server_work_for_buffers(
3803        &mut self,
3804        buffers: impl IntoIterator<Item = Entity<Buffer>>,
3805        cx: &mut Context<Self>,
3806    ) {
3807        self.lsp_store.update(cx, |lsp_store, cx| {
3808            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3809        })
3810    }
3811
3812    pub fn cancel_language_server_work(
3813        &mut self,
3814        server_id: LanguageServerId,
3815        token_to_cancel: Option<ProgressToken>,
3816        cx: &mut Context<Self>,
3817    ) {
3818        self.lsp_store.update(cx, |lsp_store, cx| {
3819            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3820        })
3821    }
3822
3823    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3824        self.buffer_ordered_messages_tx
3825            .unbounded_send(message)
3826            .map_err(|e| anyhow!(e))
3827    }
3828
3829    pub fn available_toolchains(
3830        &self,
3831        path: ProjectPath,
3832        language_name: LanguageName,
3833        cx: &App,
3834    ) -> Task<Option<Toolchains>> {
3835        if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3836            cx.spawn(async move |cx| {
3837                toolchain_store
3838                    .update(cx, |this, cx| this.list_toolchains(path, language_name, cx))
3839                    .ok()?
3840                    .await
3841            })
3842        } else {
3843            Task::ready(None)
3844        }
3845    }
3846
3847    pub async fn toolchain_metadata(
3848        languages: Arc<LanguageRegistry>,
3849        language_name: LanguageName,
3850    ) -> Option<ToolchainMetadata> {
3851        languages
3852            .language_for_name(language_name.as_ref())
3853            .await
3854            .ok()?
3855            .toolchain_lister()
3856            .map(|lister| lister.meta())
3857    }
3858
3859    pub fn add_toolchain(
3860        &self,
3861        toolchain: Toolchain,
3862        scope: ToolchainScope,
3863        cx: &mut Context<Self>,
3864    ) {
3865        maybe!({
3866            self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3867                this.add_toolchain(toolchain, scope, cx);
3868            });
3869            Some(())
3870        });
3871    }
3872
3873    pub fn remove_toolchain(
3874        &self,
3875        toolchain: Toolchain,
3876        scope: ToolchainScope,
3877        cx: &mut Context<Self>,
3878    ) {
3879        maybe!({
3880            self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3881                this.remove_toolchain(toolchain, scope, cx);
3882            });
3883            Some(())
3884        });
3885    }
3886
3887    pub fn user_toolchains(
3888        &self,
3889        cx: &App,
3890    ) -> Option<BTreeMap<ToolchainScope, IndexSet<Toolchain>>> {
3891        Some(self.toolchain_store.as_ref()?.read(cx).user_toolchains())
3892    }
3893
3894    pub fn resolve_toolchain(
3895        &self,
3896        path: PathBuf,
3897        language_name: LanguageName,
3898        cx: &App,
3899    ) -> Task<Result<Toolchain>> {
3900        if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3901            cx.spawn(async move |cx| {
3902                toolchain_store
3903                    .update(cx, |this, cx| {
3904                        this.resolve_toolchain(path, language_name, cx)
3905                    })?
3906                    .await
3907            })
3908        } else {
3909            Task::ready(Err(anyhow!("This project does not support toolchains")))
3910        }
3911    }
3912
3913    pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
3914        self.toolchain_store.clone()
3915    }
3916    pub fn activate_toolchain(
3917        &self,
3918        path: ProjectPath,
3919        toolchain: Toolchain,
3920        cx: &mut App,
3921    ) -> Task<Option<()>> {
3922        let Some(toolchain_store) = self.toolchain_store.clone() else {
3923            return Task::ready(None);
3924        };
3925        toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3926    }
3927    pub fn active_toolchain(
3928        &self,
3929        path: ProjectPath,
3930        language_name: LanguageName,
3931        cx: &App,
3932    ) -> Task<Option<Toolchain>> {
3933        let Some(toolchain_store) = self.toolchain_store.clone() else {
3934            return Task::ready(None);
3935        };
3936        toolchain_store
3937            .read(cx)
3938            .active_toolchain(path, language_name, cx)
3939    }
3940    pub fn language_server_statuses<'a>(
3941        &'a self,
3942        cx: &'a App,
3943    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3944        self.lsp_store.read(cx).language_server_statuses()
3945    }
3946
3947    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3948        self.lsp_store.read(cx).last_formatting_failure()
3949    }
3950
3951    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3952        self.lsp_store
3953            .update(cx, |store, _| store.reset_last_formatting_failure());
3954    }
3955
3956    pub fn reload_buffers(
3957        &self,
3958        buffers: HashSet<Entity<Buffer>>,
3959        push_to_history: bool,
3960        cx: &mut Context<Self>,
3961    ) -> Task<Result<ProjectTransaction>> {
3962        self.buffer_store.update(cx, |buffer_store, cx| {
3963            buffer_store.reload_buffers(buffers, push_to_history, cx)
3964        })
3965    }
3966
3967    pub fn reload_images(
3968        &self,
3969        images: HashSet<Entity<ImageItem>>,
3970        cx: &mut Context<Self>,
3971    ) -> Task<Result<()>> {
3972        self.image_store
3973            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3974    }
3975
3976    pub fn format(
3977        &mut self,
3978        buffers: HashSet<Entity<Buffer>>,
3979        target: LspFormatTarget,
3980        push_to_history: bool,
3981        trigger: lsp_store::FormatTrigger,
3982        cx: &mut Context<Project>,
3983    ) -> Task<anyhow::Result<ProjectTransaction>> {
3984        self.lsp_store.update(cx, |lsp_store, cx| {
3985            lsp_store.format(buffers, target, push_to_history, trigger, cx)
3986        })
3987    }
3988
3989    pub fn definitions<T: ToPointUtf16>(
3990        &mut self,
3991        buffer: &Entity<Buffer>,
3992        position: T,
3993        cx: &mut Context<Self>,
3994    ) -> Task<Result<Option<Vec<LocationLink>>>> {
3995        let position = position.to_point_utf16(buffer.read(cx));
3996        let guard = self.retain_remotely_created_models(cx);
3997        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3998            lsp_store.definitions(buffer, position, cx)
3999        });
4000        cx.background_spawn(async move {
4001            let result = task.await;
4002            drop(guard);
4003            result
4004        })
4005    }
4006
4007    pub fn declarations<T: ToPointUtf16>(
4008        &mut self,
4009        buffer: &Entity<Buffer>,
4010        position: T,
4011        cx: &mut Context<Self>,
4012    ) -> Task<Result<Option<Vec<LocationLink>>>> {
4013        let position = position.to_point_utf16(buffer.read(cx));
4014        let guard = self.retain_remotely_created_models(cx);
4015        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4016            lsp_store.declarations(buffer, position, cx)
4017        });
4018        cx.background_spawn(async move {
4019            let result = task.await;
4020            drop(guard);
4021            result
4022        })
4023    }
4024
4025    pub fn type_definitions<T: ToPointUtf16>(
4026        &mut self,
4027        buffer: &Entity<Buffer>,
4028        position: T,
4029        cx: &mut Context<Self>,
4030    ) -> Task<Result<Option<Vec<LocationLink>>>> {
4031        let position = position.to_point_utf16(buffer.read(cx));
4032        let guard = self.retain_remotely_created_models(cx);
4033        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4034            lsp_store.type_definitions(buffer, position, cx)
4035        });
4036        cx.background_spawn(async move {
4037            let result = task.await;
4038            drop(guard);
4039            result
4040        })
4041    }
4042
4043    pub fn implementations<T: ToPointUtf16>(
4044        &mut self,
4045        buffer: &Entity<Buffer>,
4046        position: T,
4047        cx: &mut Context<Self>,
4048    ) -> Task<Result<Option<Vec<LocationLink>>>> {
4049        let position = position.to_point_utf16(buffer.read(cx));
4050        let guard = self.retain_remotely_created_models(cx);
4051        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4052            lsp_store.implementations(buffer, position, cx)
4053        });
4054        cx.background_spawn(async move {
4055            let result = task.await;
4056            drop(guard);
4057            result
4058        })
4059    }
4060
4061    pub fn references<T: ToPointUtf16>(
4062        &mut self,
4063        buffer: &Entity<Buffer>,
4064        position: T,
4065        cx: &mut Context<Self>,
4066    ) -> Task<Result<Option<Vec<Location>>>> {
4067        let position = position.to_point_utf16(buffer.read(cx));
4068        let guard = self.retain_remotely_created_models(cx);
4069        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4070            lsp_store.references(buffer, position, cx)
4071        });
4072        cx.background_spawn(async move {
4073            let result = task.await;
4074            drop(guard);
4075            result
4076        })
4077    }
4078
4079    pub fn document_highlights<T: ToPointUtf16>(
4080        &mut self,
4081        buffer: &Entity<Buffer>,
4082        position: T,
4083        cx: &mut Context<Self>,
4084    ) -> Task<Result<Vec<DocumentHighlight>>> {
4085        let position = position.to_point_utf16(buffer.read(cx));
4086        self.request_lsp(
4087            buffer.clone(),
4088            LanguageServerToQuery::FirstCapable,
4089            GetDocumentHighlights { position },
4090            cx,
4091        )
4092    }
4093
4094    pub fn document_symbols(
4095        &mut self,
4096        buffer: &Entity<Buffer>,
4097        cx: &mut Context<Self>,
4098    ) -> Task<Result<Vec<DocumentSymbol>>> {
4099        self.request_lsp(
4100            buffer.clone(),
4101            LanguageServerToQuery::FirstCapable,
4102            GetDocumentSymbols,
4103            cx,
4104        )
4105    }
4106
4107    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
4108        self.lsp_store
4109            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
4110    }
4111
4112    pub fn open_buffer_for_symbol(
4113        &mut self,
4114        symbol: &Symbol,
4115        cx: &mut Context<Self>,
4116    ) -> Task<Result<Entity<Buffer>>> {
4117        self.lsp_store.update(cx, |lsp_store, cx| {
4118            lsp_store.open_buffer_for_symbol(symbol, cx)
4119        })
4120    }
4121
4122    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
4123        let guard = self.retain_remotely_created_models(cx);
4124        let Some(remote) = self.remote_client.as_ref() else {
4125            return Task::ready(Err(anyhow!("not an ssh project")));
4126        };
4127
4128        let proto_client = remote.read(cx).proto_client();
4129
4130        cx.spawn(async move |project, cx| {
4131            let buffer = proto_client
4132                .request(proto::OpenServerSettings {
4133                    project_id: REMOTE_SERVER_PROJECT_ID,
4134                })
4135                .await?;
4136
4137            let buffer = project
4138                .update(cx, |project, cx| {
4139                    project.buffer_store.update(cx, |buffer_store, cx| {
4140                        anyhow::Ok(
4141                            buffer_store
4142                                .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
4143                        )
4144                    })
4145                })??
4146                .await;
4147
4148            drop(guard);
4149            buffer
4150        })
4151    }
4152
4153    pub fn open_local_buffer_via_lsp(
4154        &mut self,
4155        abs_path: lsp::Uri,
4156        language_server_id: LanguageServerId,
4157        cx: &mut Context<Self>,
4158    ) -> Task<Result<Entity<Buffer>>> {
4159        self.lsp_store.update(cx, |lsp_store, cx| {
4160            lsp_store.open_local_buffer_via_lsp(abs_path, language_server_id, cx)
4161        })
4162    }
4163
4164    pub fn hover<T: ToPointUtf16>(
4165        &self,
4166        buffer: &Entity<Buffer>,
4167        position: T,
4168        cx: &mut Context<Self>,
4169    ) -> Task<Option<Vec<Hover>>> {
4170        let position = position.to_point_utf16(buffer.read(cx));
4171        self.lsp_store
4172            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
4173    }
4174
4175    pub fn linked_edits(
4176        &self,
4177        buffer: &Entity<Buffer>,
4178        position: Anchor,
4179        cx: &mut Context<Self>,
4180    ) -> Task<Result<Vec<Range<Anchor>>>> {
4181        self.lsp_store.update(cx, |lsp_store, cx| {
4182            lsp_store.linked_edits(buffer, position, cx)
4183        })
4184    }
4185
4186    pub fn completions<T: ToOffset + ToPointUtf16>(
4187        &self,
4188        buffer: &Entity<Buffer>,
4189        position: T,
4190        context: CompletionContext,
4191        cx: &mut Context<Self>,
4192    ) -> Task<Result<Vec<CompletionResponse>>> {
4193        let position = position.to_point_utf16(buffer.read(cx));
4194        self.lsp_store.update(cx, |lsp_store, cx| {
4195            lsp_store.completions(buffer, position, context, cx)
4196        })
4197    }
4198
4199    pub fn code_actions<T: Clone + ToOffset>(
4200        &mut self,
4201        buffer_handle: &Entity<Buffer>,
4202        range: Range<T>,
4203        kinds: Option<Vec<CodeActionKind>>,
4204        cx: &mut Context<Self>,
4205    ) -> Task<Result<Option<Vec<CodeAction>>>> {
4206        let buffer = buffer_handle.read(cx);
4207        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4208        self.lsp_store.update(cx, |lsp_store, cx| {
4209            lsp_store.code_actions(buffer_handle, range, kinds, cx)
4210        })
4211    }
4212
4213    pub fn code_lens_actions<T: Clone + ToOffset>(
4214        &mut self,
4215        buffer: &Entity<Buffer>,
4216        range: Range<T>,
4217        cx: &mut Context<Self>,
4218    ) -> Task<Result<Option<Vec<CodeAction>>>> {
4219        let snapshot = buffer.read(cx).snapshot();
4220        let range = range.to_point(&snapshot);
4221        let range_start = snapshot.anchor_before(range.start);
4222        let range_end = if range.start == range.end {
4223            range_start
4224        } else {
4225            snapshot.anchor_after(range.end)
4226        };
4227        let range = range_start..range_end;
4228        let code_lens_actions = self
4229            .lsp_store
4230            .update(cx, |lsp_store, cx| lsp_store.code_lens_actions(buffer, cx));
4231
4232        cx.background_spawn(async move {
4233            let mut code_lens_actions = code_lens_actions
4234                .await
4235                .map_err(|e| anyhow!("code lens fetch failed: {e:#}"))?;
4236            if let Some(code_lens_actions) = &mut code_lens_actions {
4237                code_lens_actions.retain(|code_lens_action| {
4238                    range
4239                        .start
4240                        .cmp(&code_lens_action.range.start, &snapshot)
4241                        .is_ge()
4242                        && range
4243                            .end
4244                            .cmp(&code_lens_action.range.end, &snapshot)
4245                            .is_le()
4246                });
4247            }
4248            Ok(code_lens_actions)
4249        })
4250    }
4251
4252    pub fn apply_code_action(
4253        &self,
4254        buffer_handle: Entity<Buffer>,
4255        action: CodeAction,
4256        push_to_history: bool,
4257        cx: &mut Context<Self>,
4258    ) -> Task<Result<ProjectTransaction>> {
4259        self.lsp_store.update(cx, |lsp_store, cx| {
4260            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
4261        })
4262    }
4263
4264    pub fn apply_code_action_kind(
4265        &self,
4266        buffers: HashSet<Entity<Buffer>>,
4267        kind: CodeActionKind,
4268        push_to_history: bool,
4269        cx: &mut Context<Self>,
4270    ) -> Task<Result<ProjectTransaction>> {
4271        self.lsp_store.update(cx, |lsp_store, cx| {
4272            lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
4273        })
4274    }
4275
4276    pub fn prepare_rename<T: ToPointUtf16>(
4277        &mut self,
4278        buffer: Entity<Buffer>,
4279        position: T,
4280        cx: &mut Context<Self>,
4281    ) -> Task<Result<PrepareRenameResponse>> {
4282        let position = position.to_point_utf16(buffer.read(cx));
4283        self.request_lsp(
4284            buffer,
4285            LanguageServerToQuery::FirstCapable,
4286            PrepareRename { position },
4287            cx,
4288        )
4289    }
4290
4291    pub fn perform_rename<T: ToPointUtf16>(
4292        &mut self,
4293        buffer: Entity<Buffer>,
4294        position: T,
4295        new_name: String,
4296        cx: &mut Context<Self>,
4297    ) -> Task<Result<ProjectTransaction>> {
4298        let push_to_history = true;
4299        let position = position.to_point_utf16(buffer.read(cx));
4300        self.request_lsp(
4301            buffer,
4302            LanguageServerToQuery::FirstCapable,
4303            PerformRename {
4304                position,
4305                new_name,
4306                push_to_history,
4307            },
4308            cx,
4309        )
4310    }
4311
4312    pub fn on_type_format<T: ToPointUtf16>(
4313        &mut self,
4314        buffer: Entity<Buffer>,
4315        position: T,
4316        trigger: String,
4317        push_to_history: bool,
4318        cx: &mut Context<Self>,
4319    ) -> Task<Result<Option<Transaction>>> {
4320        self.lsp_store.update(cx, |lsp_store, cx| {
4321            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
4322        })
4323    }
4324
4325    pub fn inline_values(
4326        &mut self,
4327        session: Entity<Session>,
4328        active_stack_frame: ActiveStackFrame,
4329        buffer_handle: Entity<Buffer>,
4330        range: Range<text::Anchor>,
4331        cx: &mut Context<Self>,
4332    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
4333        let snapshot = buffer_handle.read(cx).snapshot();
4334
4335        let captures =
4336            snapshot.debug_variables_query(Anchor::min_for_buffer(snapshot.remote_id())..range.end);
4337
4338        let row = snapshot
4339            .summary_for_anchor::<text::PointUtf16>(&range.end)
4340            .row as usize;
4341
4342        let inline_value_locations = provide_inline_values(captures, &snapshot, row);
4343
4344        let stack_frame_id = active_stack_frame.stack_frame_id;
4345        cx.spawn(async move |this, cx| {
4346            this.update(cx, |project, cx| {
4347                project.dap_store().update(cx, |dap_store, cx| {
4348                    dap_store.resolve_inline_value_locations(
4349                        session,
4350                        stack_frame_id,
4351                        buffer_handle,
4352                        inline_value_locations,
4353                        cx,
4354                    )
4355                })
4356            })?
4357            .await
4358        })
4359    }
4360
4361    fn search_impl(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> SearchResultsHandle {
4362        let client: Option<(AnyProtoClient, _)> = if let Some(ssh_client) = &self.remote_client {
4363            Some((ssh_client.read(cx).proto_client(), 0))
4364        } else if let Some(remote_id) = self.remote_id() {
4365            self.is_local()
4366                .not()
4367                .then(|| (self.collab_client.clone().into(), remote_id))
4368        } else {
4369            None
4370        };
4371        let searcher = if query.is_opened_only() {
4372            project_search::Search::open_buffers_only(
4373                self.buffer_store.clone(),
4374                self.worktree_store.clone(),
4375                project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4376            )
4377        } else {
4378            match client {
4379                Some((client, remote_id)) => project_search::Search::remote(
4380                    self.buffer_store.clone(),
4381                    self.worktree_store.clone(),
4382                    project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4383                    (client, remote_id, self.remotely_created_models.clone()),
4384                ),
4385                None => project_search::Search::local(
4386                    self.fs.clone(),
4387                    self.buffer_store.clone(),
4388                    self.worktree_store.clone(),
4389                    project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4390                    cx,
4391                ),
4392            }
4393        };
4394        searcher.into_handle(query, cx)
4395    }
4396
4397    pub fn search(
4398        &mut self,
4399        query: SearchQuery,
4400        cx: &mut Context<Self>,
4401    ) -> SearchResults<SearchResult> {
4402        self.search_impl(query, cx).results(cx)
4403    }
4404
4405    pub fn request_lsp<R: LspCommand>(
4406        &mut self,
4407        buffer_handle: Entity<Buffer>,
4408        server: LanguageServerToQuery,
4409        request: R,
4410        cx: &mut Context<Self>,
4411    ) -> Task<Result<R::Response>>
4412    where
4413        <R::LspRequest as lsp::request::Request>::Result: Send,
4414        <R::LspRequest as lsp::request::Request>::Params: Send,
4415    {
4416        let guard = self.retain_remotely_created_models(cx);
4417        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4418            lsp_store.request_lsp(buffer_handle, server, request, cx)
4419        });
4420        cx.background_spawn(async move {
4421            let result = task.await;
4422            drop(guard);
4423            result
4424        })
4425    }
4426
4427    /// Move a worktree to a new position in the worktree order.
4428    ///
4429    /// The worktree will moved to the opposite side of the destination worktree.
4430    ///
4431    /// # Example
4432    ///
4433    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4434    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4435    ///
4436    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4437    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4438    ///
4439    /// # Errors
4440    ///
4441    /// An error will be returned if the worktree or destination worktree are not found.
4442    pub fn move_worktree(
4443        &mut self,
4444        source: WorktreeId,
4445        destination: WorktreeId,
4446        cx: &mut Context<Self>,
4447    ) -> Result<()> {
4448        self.worktree_store.update(cx, |worktree_store, cx| {
4449            worktree_store.move_worktree(source, destination, cx)
4450        })
4451    }
4452
4453    /// Attempts to convert the input path to a WSL path if this is a wsl remote project and the input path is a host windows path.
4454    pub fn try_windows_path_to_wsl(
4455        &self,
4456        abs_path: &Path,
4457        cx: &App,
4458    ) -> impl Future<Output = Result<PathBuf>> + use<> {
4459        let fut = if cfg!(windows)
4460            && let (
4461                ProjectClientState::Local | ProjectClientState::Shared { .. },
4462                Some(remote_client),
4463            ) = (&self.client_state, &self.remote_client)
4464            && let RemoteConnectionOptions::Wsl(wsl) = remote_client.read(cx).connection_options()
4465        {
4466            Either::Left(wsl.abs_windows_path_to_wsl_path(abs_path))
4467        } else {
4468            Either::Right(abs_path.to_owned())
4469        };
4470        async move {
4471            match fut {
4472                Either::Left(fut) => fut.await.map(Into::into),
4473                Either::Right(path) => Ok(path),
4474            }
4475        }
4476    }
4477
4478    pub fn find_or_create_worktree(
4479        &mut self,
4480        abs_path: impl AsRef<Path>,
4481        visible: bool,
4482        cx: &mut Context<Self>,
4483    ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
4484        self.worktree_store.update(cx, |worktree_store, cx| {
4485            worktree_store.find_or_create_worktree(abs_path, visible, cx)
4486        })
4487    }
4488
4489    pub fn find_worktree(
4490        &self,
4491        abs_path: &Path,
4492        cx: &App,
4493    ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
4494        self.worktree_store.read(cx).find_worktree(abs_path, cx)
4495    }
4496
4497    pub fn is_shared(&self) -> bool {
4498        match &self.client_state {
4499            ProjectClientState::Shared { .. } => true,
4500            ProjectClientState::Local => false,
4501            ProjectClientState::Remote { .. } => true,
4502        }
4503    }
4504
4505    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4506    pub fn resolve_path_in_buffer(
4507        &self,
4508        path: &str,
4509        buffer: &Entity<Buffer>,
4510        cx: &mut Context<Self>,
4511    ) -> Task<Option<ResolvedPath>> {
4512        if util::paths::is_absolute(path, self.path_style(cx)) || path.starts_with("~") {
4513            self.resolve_abs_path(path, cx)
4514        } else {
4515            self.resolve_path_in_worktrees(path, buffer, cx)
4516        }
4517    }
4518
4519    pub fn resolve_abs_file_path(
4520        &self,
4521        path: &str,
4522        cx: &mut Context<Self>,
4523    ) -> Task<Option<ResolvedPath>> {
4524        let resolve_task = self.resolve_abs_path(path, cx);
4525        cx.background_spawn(async move {
4526            let resolved_path = resolve_task.await;
4527            resolved_path.filter(|path| path.is_file())
4528        })
4529    }
4530
4531    pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4532        if self.is_local() {
4533            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4534            let fs = self.fs.clone();
4535            cx.background_spawn(async move {
4536                let metadata = fs.metadata(&expanded).await.ok().flatten();
4537
4538                metadata.map(|metadata| ResolvedPath::AbsPath {
4539                    path: expanded.to_string_lossy().into_owned(),
4540                    is_dir: metadata.is_dir,
4541                })
4542            })
4543        } else if let Some(ssh_client) = self.remote_client.as_ref() {
4544            let request = ssh_client
4545                .read(cx)
4546                .proto_client()
4547                .request(proto::GetPathMetadata {
4548                    project_id: REMOTE_SERVER_PROJECT_ID,
4549                    path: path.into(),
4550                });
4551            cx.background_spawn(async move {
4552                let response = request.await.log_err()?;
4553                if response.exists {
4554                    Some(ResolvedPath::AbsPath {
4555                        path: response.path,
4556                        is_dir: response.is_dir,
4557                    })
4558                } else {
4559                    None
4560                }
4561            })
4562        } else {
4563            Task::ready(None)
4564        }
4565    }
4566
4567    fn resolve_path_in_worktrees(
4568        &self,
4569        path: &str,
4570        buffer: &Entity<Buffer>,
4571        cx: &mut Context<Self>,
4572    ) -> Task<Option<ResolvedPath>> {
4573        let mut candidates = vec![];
4574        let path_style = self.path_style(cx);
4575        if let Ok(path) = RelPath::new(path.as_ref(), path_style) {
4576            candidates.push(path.into_arc());
4577        }
4578
4579        if let Some(file) = buffer.read(cx).file()
4580            && let Some(dir) = file.path().parent()
4581        {
4582            if let Some(joined) = path_style.join(&*dir.display(path_style), path)
4583                && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
4584            {
4585                candidates.push(joined.into_arc());
4586            }
4587        }
4588
4589        let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4590        let worktrees_with_ids: Vec<_> = self
4591            .worktrees(cx)
4592            .map(|worktree| {
4593                let id = worktree.read(cx).id();
4594                (worktree, id)
4595            })
4596            .collect();
4597
4598        cx.spawn(async move |_, cx| {
4599            if let Some(buffer_worktree_id) = buffer_worktree_id
4600                && let Some((worktree, _)) = worktrees_with_ids
4601                    .iter()
4602                    .find(|(_, id)| *id == buffer_worktree_id)
4603            {
4604                for candidate in candidates.iter() {
4605                    if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4606                        return Some(path);
4607                    }
4608                }
4609            }
4610            for (worktree, id) in worktrees_with_ids {
4611                if Some(id) == buffer_worktree_id {
4612                    continue;
4613                }
4614                for candidate in candidates.iter() {
4615                    if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4616                        return Some(path);
4617                    }
4618                }
4619            }
4620            None
4621        })
4622    }
4623
4624    fn resolve_path_in_worktree(
4625        worktree: &Entity<Worktree>,
4626        path: &RelPath,
4627        cx: &mut AsyncApp,
4628    ) -> Option<ResolvedPath> {
4629        worktree.read_with(cx, |worktree, _| {
4630            worktree.entry_for_path(path).map(|entry| {
4631                let project_path = ProjectPath {
4632                    worktree_id: worktree.id(),
4633                    path: entry.path.clone(),
4634                };
4635                ResolvedPath::ProjectPath {
4636                    project_path,
4637                    is_dir: entry.is_dir(),
4638                }
4639            })
4640        })
4641    }
4642
4643    pub fn list_directory(
4644        &self,
4645        query: String,
4646        cx: &mut Context<Self>,
4647    ) -> Task<Result<Vec<DirectoryItem>>> {
4648        if self.is_local() {
4649            DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4650        } else if let Some(session) = self.remote_client.as_ref() {
4651            let request = proto::ListRemoteDirectory {
4652                dev_server_id: REMOTE_SERVER_PROJECT_ID,
4653                path: query,
4654                config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4655            };
4656
4657            let response = session.read(cx).proto_client().request(request);
4658            cx.background_spawn(async move {
4659                let proto::ListRemoteDirectoryResponse {
4660                    entries,
4661                    entry_info,
4662                } = response.await?;
4663                Ok(entries
4664                    .into_iter()
4665                    .zip(entry_info)
4666                    .map(|(entry, info)| DirectoryItem {
4667                        path: PathBuf::from(entry),
4668                        is_dir: info.is_dir,
4669                    })
4670                    .collect())
4671            })
4672        } else {
4673            Task::ready(Err(anyhow!("cannot list directory in remote project")))
4674        }
4675    }
4676
4677    pub fn create_worktree(
4678        &mut self,
4679        abs_path: impl AsRef<Path>,
4680        visible: bool,
4681        cx: &mut Context<Self>,
4682    ) -> Task<Result<Entity<Worktree>>> {
4683        self.worktree_store.update(cx, |worktree_store, cx| {
4684            worktree_store.create_worktree(abs_path, visible, cx)
4685        })
4686    }
4687
4688    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4689        self.worktree_store.update(cx, |worktree_store, cx| {
4690            worktree_store.remove_worktree(id_to_remove, cx);
4691        });
4692    }
4693
4694    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4695        self.worktree_store.update(cx, |worktree_store, cx| {
4696            worktree_store.add(worktree, cx);
4697        });
4698    }
4699
4700    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4701        let new_active_entry = entry.and_then(|project_path| {
4702            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4703            let entry = worktree.read(cx).entry_for_path(&project_path.path)?;
4704            Some(entry.id)
4705        });
4706        if new_active_entry != self.active_entry {
4707            self.active_entry = new_active_entry;
4708            self.lsp_store.update(cx, |lsp_store, _| {
4709                lsp_store.set_active_entry(new_active_entry);
4710            });
4711            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4712        }
4713    }
4714
4715    pub fn language_servers_running_disk_based_diagnostics<'a>(
4716        &'a self,
4717        cx: &'a App,
4718    ) -> impl Iterator<Item = LanguageServerId> + 'a {
4719        self.lsp_store
4720            .read(cx)
4721            .language_servers_running_disk_based_diagnostics()
4722    }
4723
4724    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4725        self.lsp_store
4726            .read(cx)
4727            .diagnostic_summary(include_ignored, cx)
4728    }
4729
4730    /// Returns a summary of the diagnostics for the provided project path only.
4731    pub fn diagnostic_summary_for_path(&self, path: &ProjectPath, cx: &App) -> DiagnosticSummary {
4732        self.lsp_store
4733            .read(cx)
4734            .diagnostic_summary_for_path(path, cx)
4735    }
4736
4737    pub fn diagnostic_summaries<'a>(
4738        &'a self,
4739        include_ignored: bool,
4740        cx: &'a App,
4741    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4742        self.lsp_store
4743            .read(cx)
4744            .diagnostic_summaries(include_ignored, cx)
4745    }
4746
4747    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4748        self.active_entry
4749    }
4750
4751    pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
4752        self.worktree_store.read(cx).entry_for_path(path, cx)
4753    }
4754
4755    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4756        let worktree = self.worktree_for_entry(entry_id, cx)?;
4757        let worktree = worktree.read(cx);
4758        let worktree_id = worktree.id();
4759        let path = worktree.entry_for_id(entry_id)?.path.clone();
4760        Some(ProjectPath { worktree_id, path })
4761    }
4762
4763    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4764        Some(
4765            self.worktree_for_id(project_path.worktree_id, cx)?
4766                .read(cx)
4767                .absolutize(&project_path.path),
4768        )
4769    }
4770
4771    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4772    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4773    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4774    /// the first visible worktree that has an entry for that relative path.
4775    ///
4776    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4777    /// root name from paths.
4778    ///
4779    /// # Arguments
4780    ///
4781    /// * `path` - An absolute path, or a full path that starts with a worktree root name, or a
4782    ///   relative path within a visible worktree.
4783    /// * `cx` - A reference to the `AppContext`.
4784    ///
4785    /// # Returns
4786    ///
4787    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4788    pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4789        let path_style = self.path_style(cx);
4790        let path = path.as_ref();
4791        let worktree_store = self.worktree_store.read(cx);
4792
4793        if is_absolute(&path.to_string_lossy(), path_style) {
4794            for worktree in worktree_store.visible_worktrees(cx) {
4795                let worktree_abs_path = worktree.read(cx).abs_path();
4796
4797                if let Ok(relative_path) = path.strip_prefix(worktree_abs_path)
4798                    && let Ok(path) = RelPath::new(relative_path, path_style)
4799                {
4800                    return Some(ProjectPath {
4801                        worktree_id: worktree.read(cx).id(),
4802                        path: path.into_arc(),
4803                    });
4804                }
4805            }
4806        } else {
4807            for worktree in worktree_store.visible_worktrees(cx) {
4808                let worktree = worktree.read(cx);
4809                if let Ok(rel_path) = RelPath::new(path, path_style) {
4810                    if let Some(entry) = worktree.entry_for_path(&rel_path) {
4811                        return Some(ProjectPath {
4812                            worktree_id: worktree.id(),
4813                            path: entry.path.clone(),
4814                        });
4815                    }
4816                }
4817            }
4818
4819            for worktree in worktree_store.visible_worktrees(cx) {
4820                let worktree_root_name = worktree.read(cx).root_name();
4821                if let Ok(relative_path) = path.strip_prefix(worktree_root_name.as_std_path())
4822                    && let Ok(path) = RelPath::new(relative_path, path_style)
4823                {
4824                    return Some(ProjectPath {
4825                        worktree_id: worktree.read(cx).id(),
4826                        path: path.into_arc(),
4827                    });
4828                }
4829            }
4830        }
4831
4832        None
4833    }
4834
4835    /// If there's only one visible worktree, returns the given worktree-relative path with no prefix.
4836    ///
4837    /// Otherwise, returns the full path for the project path (obtained by prefixing the worktree-relative path with the name of the worktree).
4838    pub fn short_full_path_for_project_path(
4839        &self,
4840        project_path: &ProjectPath,
4841        cx: &App,
4842    ) -> Option<String> {
4843        let path_style = self.path_style(cx);
4844        if self.visible_worktrees(cx).take(2).count() < 2 {
4845            return Some(project_path.path.display(path_style).to_string());
4846        }
4847        self.worktree_for_id(project_path.worktree_id, cx)
4848            .map(|worktree| {
4849                let worktree_name = worktree.read(cx).root_name();
4850                worktree_name
4851                    .join(&project_path.path)
4852                    .display(path_style)
4853                    .to_string()
4854            })
4855    }
4856
4857    pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4858        self.worktree_store
4859            .read(cx)
4860            .project_path_for_absolute_path(abs_path, cx)
4861    }
4862
4863    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4864        Some(
4865            self.worktree_for_id(project_path.worktree_id, cx)?
4866                .read(cx)
4867                .abs_path()
4868                .to_path_buf(),
4869        )
4870    }
4871
4872    pub fn blame_buffer(
4873        &self,
4874        buffer: &Entity<Buffer>,
4875        version: Option<clock::Global>,
4876        cx: &mut App,
4877    ) -> Task<Result<Option<Blame>>> {
4878        self.git_store.update(cx, |git_store, cx| {
4879            git_store.blame_buffer(buffer, version, cx)
4880        })
4881    }
4882
4883    pub fn get_permalink_to_line(
4884        &self,
4885        buffer: &Entity<Buffer>,
4886        selection: Range<u32>,
4887        cx: &mut App,
4888    ) -> Task<Result<url::Url>> {
4889        self.git_store.update(cx, |git_store, cx| {
4890            git_store.get_permalink_to_line(buffer, selection, cx)
4891        })
4892    }
4893
4894    // RPC message handlers
4895
4896    async fn handle_unshare_project(
4897        this: Entity<Self>,
4898        _: TypedEnvelope<proto::UnshareProject>,
4899        mut cx: AsyncApp,
4900    ) -> Result<()> {
4901        this.update(&mut cx, |this, cx| {
4902            if this.is_local() || this.is_via_remote_server() {
4903                this.unshare(cx)?;
4904            } else {
4905                this.disconnected_from_host(cx);
4906            }
4907            Ok(())
4908        })
4909    }
4910
4911    async fn handle_add_collaborator(
4912        this: Entity<Self>,
4913        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4914        mut cx: AsyncApp,
4915    ) -> Result<()> {
4916        let collaborator = envelope
4917            .payload
4918            .collaborator
4919            .take()
4920            .context("empty collaborator")?;
4921
4922        let collaborator = Collaborator::from_proto(collaborator)?;
4923        this.update(&mut cx, |this, cx| {
4924            this.buffer_store.update(cx, |buffer_store, _| {
4925                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4926            });
4927            this.breakpoint_store.read(cx).broadcast();
4928            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4929            this.collaborators
4930                .insert(collaborator.peer_id, collaborator);
4931        });
4932
4933        Ok(())
4934    }
4935
4936    async fn handle_update_project_collaborator(
4937        this: Entity<Self>,
4938        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4939        mut cx: AsyncApp,
4940    ) -> Result<()> {
4941        let old_peer_id = envelope
4942            .payload
4943            .old_peer_id
4944            .context("missing old peer id")?;
4945        let new_peer_id = envelope
4946            .payload
4947            .new_peer_id
4948            .context("missing new peer id")?;
4949        this.update(&mut cx, |this, cx| {
4950            let collaborator = this
4951                .collaborators
4952                .remove(&old_peer_id)
4953                .context("received UpdateProjectCollaborator for unknown peer")?;
4954            let is_host = collaborator.is_host;
4955            this.collaborators.insert(new_peer_id, collaborator);
4956
4957            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4958            this.buffer_store.update(cx, |buffer_store, _| {
4959                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4960            });
4961
4962            if is_host {
4963                this.buffer_store
4964                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4965                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4966                    .unwrap();
4967                cx.emit(Event::HostReshared);
4968            }
4969
4970            cx.emit(Event::CollaboratorUpdated {
4971                old_peer_id,
4972                new_peer_id,
4973            });
4974            Ok(())
4975        })
4976    }
4977
4978    async fn handle_remove_collaborator(
4979        this: Entity<Self>,
4980        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4981        mut cx: AsyncApp,
4982    ) -> Result<()> {
4983        this.update(&mut cx, |this, cx| {
4984            let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4985            let replica_id = this
4986                .collaborators
4987                .remove(&peer_id)
4988                .with_context(|| format!("unknown peer {peer_id:?}"))?
4989                .replica_id;
4990            this.buffer_store.update(cx, |buffer_store, cx| {
4991                buffer_store.forget_shared_buffers_for(&peer_id);
4992                for buffer in buffer_store.buffers() {
4993                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4994                }
4995            });
4996            this.git_store.update(cx, |git_store, _| {
4997                git_store.forget_shared_diffs_for(&peer_id);
4998            });
4999
5000            cx.emit(Event::CollaboratorLeft(peer_id));
5001            Ok(())
5002        })
5003    }
5004
5005    async fn handle_update_project(
5006        this: Entity<Self>,
5007        envelope: TypedEnvelope<proto::UpdateProject>,
5008        mut cx: AsyncApp,
5009    ) -> Result<()> {
5010        this.update(&mut cx, |this, cx| {
5011            // Don't handle messages that were sent before the response to us joining the project
5012            if envelope.message_id > this.join_project_response_message_id {
5013                cx.update_global::<SettingsStore, _>(|store, cx| {
5014                    for worktree_metadata in &envelope.payload.worktrees {
5015                        store
5016                            .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
5017                            .log_err();
5018                    }
5019                });
5020
5021                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
5022            }
5023            Ok(())
5024        })
5025    }
5026
5027    async fn handle_toast(
5028        this: Entity<Self>,
5029        envelope: TypedEnvelope<proto::Toast>,
5030        mut cx: AsyncApp,
5031    ) -> Result<()> {
5032        this.update(&mut cx, |_, cx| {
5033            cx.emit(Event::Toast {
5034                notification_id: envelope.payload.notification_id.into(),
5035                message: envelope.payload.message,
5036                link: None,
5037            });
5038            Ok(())
5039        })
5040    }
5041
5042    async fn handle_language_server_prompt_request(
5043        this: Entity<Self>,
5044        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
5045        mut cx: AsyncApp,
5046    ) -> Result<proto::LanguageServerPromptResponse> {
5047        let (tx, rx) = smol::channel::bounded(1);
5048        let actions: Vec<_> = envelope
5049            .payload
5050            .actions
5051            .into_iter()
5052            .map(|action| MessageActionItem {
5053                title: action,
5054                properties: Default::default(),
5055            })
5056            .collect();
5057        this.update(&mut cx, |_, cx| {
5058            cx.emit(Event::LanguageServerPrompt(
5059                LanguageServerPromptRequest::new(
5060                    proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
5061                    envelope.payload.message,
5062                    actions.clone(),
5063                    envelope.payload.lsp_name,
5064                    tx,
5065                ),
5066            ));
5067
5068            anyhow::Ok(())
5069        })?;
5070
5071        // We drop `this` to avoid holding a reference in this future for too
5072        // long.
5073        // If we keep the reference, we might not drop the `Project` early
5074        // enough when closing a window and it will only get releases on the
5075        // next `flush_effects()` call.
5076        drop(this);
5077
5078        let mut rx = pin!(rx);
5079        let answer = rx.next().await;
5080
5081        Ok(LanguageServerPromptResponse {
5082            action_response: answer.and_then(|answer| {
5083                actions
5084                    .iter()
5085                    .position(|action| *action == answer)
5086                    .map(|index| index as u64)
5087            }),
5088        })
5089    }
5090
5091    async fn handle_hide_toast(
5092        this: Entity<Self>,
5093        envelope: TypedEnvelope<proto::HideToast>,
5094        mut cx: AsyncApp,
5095    ) -> Result<()> {
5096        this.update(&mut cx, |_, cx| {
5097            cx.emit(Event::HideToast {
5098                notification_id: envelope.payload.notification_id.into(),
5099            });
5100            Ok(())
5101        })
5102    }
5103
5104    // Collab sends UpdateWorktree protos as messages
5105    async fn handle_update_worktree(
5106        this: Entity<Self>,
5107        envelope: TypedEnvelope<proto::UpdateWorktree>,
5108        mut cx: AsyncApp,
5109    ) -> Result<()> {
5110        this.update(&mut cx, |project, cx| {
5111            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5112            if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
5113                worktree.update(cx, |worktree, _| {
5114                    let worktree = worktree.as_remote_mut().unwrap();
5115                    worktree.update_from_remote(envelope.payload);
5116                });
5117            }
5118            Ok(())
5119        })
5120    }
5121
5122    async fn handle_update_buffer_from_remote_server(
5123        this: Entity<Self>,
5124        envelope: TypedEnvelope<proto::UpdateBuffer>,
5125        cx: AsyncApp,
5126    ) -> Result<proto::Ack> {
5127        let buffer_store = this.read_with(&cx, |this, cx| {
5128            if let Some(remote_id) = this.remote_id() {
5129                let mut payload = envelope.payload.clone();
5130                payload.project_id = remote_id;
5131                cx.background_spawn(this.collab_client.request(payload))
5132                    .detach_and_log_err(cx);
5133            }
5134            this.buffer_store.clone()
5135        });
5136        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
5137    }
5138
5139    async fn handle_trust_worktrees(
5140        this: Entity<Self>,
5141        envelope: TypedEnvelope<proto::TrustWorktrees>,
5142        mut cx: AsyncApp,
5143    ) -> Result<proto::Ack> {
5144        if this.read_with(&cx, |project, _| project.is_via_collab()) {
5145            return Ok(proto::Ack {});
5146        }
5147
5148        let trusted_worktrees = cx
5149            .update(|cx| TrustedWorktrees::try_get_global(cx))
5150            .context("missing trusted worktrees")?;
5151        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
5152            trusted_worktrees.trust(
5153                &this.read(cx).worktree_store(),
5154                envelope
5155                    .payload
5156                    .trusted_paths
5157                    .into_iter()
5158                    .filter_map(|proto_path| PathTrust::from_proto(proto_path))
5159                    .collect(),
5160                cx,
5161            );
5162        });
5163        Ok(proto::Ack {})
5164    }
5165
5166    async fn handle_restrict_worktrees(
5167        this: Entity<Self>,
5168        envelope: TypedEnvelope<proto::RestrictWorktrees>,
5169        mut cx: AsyncApp,
5170    ) -> Result<proto::Ack> {
5171        if this.read_with(&cx, |project, _| project.is_via_collab()) {
5172            return Ok(proto::Ack {});
5173        }
5174
5175        let trusted_worktrees = cx
5176            .update(|cx| TrustedWorktrees::try_get_global(cx))
5177            .context("missing trusted worktrees")?;
5178        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
5179            let worktree_store = this.read(cx).worktree_store().downgrade();
5180            let restricted_paths = envelope
5181                .payload
5182                .worktree_ids
5183                .into_iter()
5184                .map(WorktreeId::from_proto)
5185                .map(PathTrust::Worktree)
5186                .collect::<HashSet<_>>();
5187            trusted_worktrees.restrict(worktree_store, restricted_paths, cx);
5188        });
5189        Ok(proto::Ack {})
5190    }
5191
5192    // Goes from host to client.
5193    async fn handle_find_search_candidates_chunk(
5194        this: Entity<Self>,
5195        envelope: TypedEnvelope<proto::FindSearchCandidatesChunk>,
5196        mut cx: AsyncApp,
5197    ) -> Result<proto::Ack> {
5198        let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
5199        BufferStore::handle_find_search_candidates_chunk(buffer_store, envelope, cx).await
5200    }
5201
5202    // Goes from client to host.
5203    async fn handle_find_search_candidates_cancel(
5204        this: Entity<Self>,
5205        envelope: TypedEnvelope<proto::FindSearchCandidatesCancelled>,
5206        mut cx: AsyncApp,
5207    ) -> Result<()> {
5208        let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
5209        BufferStore::handle_find_search_candidates_cancel(buffer_store, envelope, cx).await
5210    }
5211
5212    async fn handle_update_buffer(
5213        this: Entity<Self>,
5214        envelope: TypedEnvelope<proto::UpdateBuffer>,
5215        cx: AsyncApp,
5216    ) -> Result<proto::Ack> {
5217        let buffer_store = this.read_with(&cx, |this, cx| {
5218            if let Some(ssh) = &this.remote_client {
5219                let mut payload = envelope.payload.clone();
5220                payload.project_id = REMOTE_SERVER_PROJECT_ID;
5221                cx.background_spawn(ssh.read(cx).proto_client().request(payload))
5222                    .detach_and_log_err(cx);
5223            }
5224            this.buffer_store.clone()
5225        });
5226        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
5227    }
5228
5229    fn retain_remotely_created_models(
5230        &mut self,
5231        cx: &mut Context<Self>,
5232    ) -> RemotelyCreatedModelGuard {
5233        Self::retain_remotely_created_models_impl(
5234            &self.remotely_created_models,
5235            &self.buffer_store,
5236            &self.worktree_store,
5237            cx,
5238        )
5239    }
5240
5241    fn retain_remotely_created_models_impl(
5242        models: &Arc<Mutex<RemotelyCreatedModels>>,
5243        buffer_store: &Entity<BufferStore>,
5244        worktree_store: &Entity<WorktreeStore>,
5245        cx: &mut App,
5246    ) -> RemotelyCreatedModelGuard {
5247        {
5248            let mut remotely_create_models = models.lock();
5249            if remotely_create_models.retain_count == 0 {
5250                remotely_create_models.buffers = buffer_store.read(cx).buffers().collect();
5251                remotely_create_models.worktrees = worktree_store.read(cx).worktrees().collect();
5252            }
5253            remotely_create_models.retain_count += 1;
5254        }
5255        RemotelyCreatedModelGuard {
5256            remote_models: Arc::downgrade(&models),
5257        }
5258    }
5259
5260    async fn handle_create_buffer_for_peer(
5261        this: Entity<Self>,
5262        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5263        mut cx: AsyncApp,
5264    ) -> Result<()> {
5265        this.update(&mut cx, |this, cx| {
5266            this.buffer_store.update(cx, |buffer_store, cx| {
5267                buffer_store.handle_create_buffer_for_peer(
5268                    envelope,
5269                    this.replica_id(),
5270                    this.capability(),
5271                    cx,
5272                )
5273            })
5274        })
5275    }
5276
5277    async fn handle_toggle_lsp_logs(
5278        project: Entity<Self>,
5279        envelope: TypedEnvelope<proto::ToggleLspLogs>,
5280        mut cx: AsyncApp,
5281    ) -> Result<()> {
5282        let toggled_log_kind =
5283            match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
5284                .context("invalid log type")?
5285            {
5286                proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
5287                proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
5288                proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
5289            };
5290        project.update(&mut cx, |_, cx| {
5291            cx.emit(Event::ToggleLspLogs {
5292                server_id: LanguageServerId::from_proto(envelope.payload.server_id),
5293                enabled: envelope.payload.enabled,
5294                toggled_log_kind,
5295            })
5296        });
5297        Ok(())
5298    }
5299
5300    async fn handle_synchronize_buffers(
5301        this: Entity<Self>,
5302        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5303        mut cx: AsyncApp,
5304    ) -> Result<proto::SynchronizeBuffersResponse> {
5305        let response = this.update(&mut cx, |this, cx| {
5306            let client = this.collab_client.clone();
5307            this.buffer_store.update(cx, |this, cx| {
5308                this.handle_synchronize_buffers(envelope, cx, client)
5309            })
5310        })?;
5311
5312        Ok(response)
5313    }
5314
5315    // Goes from client to host.
5316    async fn handle_search_candidate_buffers(
5317        this: Entity<Self>,
5318        envelope: TypedEnvelope<proto::FindSearchCandidates>,
5319        mut cx: AsyncApp,
5320    ) -> Result<proto::Ack> {
5321        let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
5322        let message = envelope.payload;
5323        let project_id = message.project_id;
5324        let path_style = this.read_with(&cx, |this, cx| this.path_style(cx));
5325        let query =
5326            SearchQuery::from_proto(message.query.context("missing query field")?, path_style)?;
5327
5328        let handle = message.handle;
5329        let buffer_store = this.read_with(&cx, |this, _| this.buffer_store().clone());
5330        let client = this.read_with(&cx, |this, _| this.client());
5331        let task = cx.spawn(async move |cx| {
5332            let results = this.update(cx, |this, cx| {
5333                this.search_impl(query, cx).matching_buffers(cx)
5334            });
5335            let (batcher, batches) = project_search::AdaptiveBatcher::new(cx.background_executor());
5336            let mut new_matches = Box::pin(results.rx);
5337
5338            let sender_task = cx.background_executor().spawn({
5339                let client = client.clone();
5340                async move {
5341                    let mut batches = std::pin::pin!(batches);
5342                    while let Some(buffer_ids) = batches.next().await {
5343                        client
5344                            .request(proto::FindSearchCandidatesChunk {
5345                                handle,
5346                                peer_id: Some(peer_id),
5347                                project_id,
5348                                variant: Some(
5349                                    proto::find_search_candidates_chunk::Variant::Matches(
5350                                        proto::FindSearchCandidatesMatches { buffer_ids },
5351                                    ),
5352                                ),
5353                            })
5354                            .await?;
5355                    }
5356                    anyhow::Ok(())
5357                }
5358            });
5359
5360            while let Some(buffer) = new_matches.next().await {
5361                let buffer_id = this.update(cx, |this, cx| {
5362                    this.create_buffer_for_peer(&buffer, peer_id, cx).to_proto()
5363                });
5364                batcher.push(buffer_id).await;
5365            }
5366            batcher.flush().await;
5367
5368            sender_task.await?;
5369
5370            let _ = client
5371                .request(proto::FindSearchCandidatesChunk {
5372                    handle,
5373                    peer_id: Some(peer_id),
5374                    project_id,
5375                    variant: Some(proto::find_search_candidates_chunk::Variant::Done(
5376                        proto::FindSearchCandidatesDone {},
5377                    )),
5378                })
5379                .await?;
5380            anyhow::Ok(())
5381        });
5382        buffer_store.update(&mut cx, |this, _| {
5383            this.register_ongoing_project_search((peer_id, handle), task);
5384        });
5385
5386        Ok(proto::Ack {})
5387    }
5388
5389    async fn handle_open_buffer_by_id(
5390        this: Entity<Self>,
5391        envelope: TypedEnvelope<proto::OpenBufferById>,
5392        mut cx: AsyncApp,
5393    ) -> Result<proto::OpenBufferResponse> {
5394        let peer_id = envelope.original_sender_id()?;
5395        let buffer_id = BufferId::new(envelope.payload.id)?;
5396        let buffer = this
5397            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))
5398            .await?;
5399        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5400    }
5401
5402    async fn handle_open_buffer_by_path(
5403        this: Entity<Self>,
5404        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5405        mut cx: AsyncApp,
5406    ) -> Result<proto::OpenBufferResponse> {
5407        let peer_id = envelope.original_sender_id()?;
5408        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5409        let path = RelPath::from_proto(&envelope.payload.path)?;
5410        let open_buffer = this
5411            .update(&mut cx, |this, cx| {
5412                this.open_buffer(ProjectPath { worktree_id, path }, cx)
5413            })
5414            .await?;
5415        Project::respond_to_open_buffer_request(this, open_buffer, peer_id, &mut cx)
5416    }
5417
5418    async fn handle_open_new_buffer(
5419        this: Entity<Self>,
5420        envelope: TypedEnvelope<proto::OpenNewBuffer>,
5421        mut cx: AsyncApp,
5422    ) -> Result<proto::OpenBufferResponse> {
5423        let buffer = this
5424            .update(&mut cx, |this, cx| this.create_buffer(None, true, cx))
5425            .await?;
5426        let peer_id = envelope.original_sender_id()?;
5427
5428        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5429    }
5430
5431    fn respond_to_open_buffer_request(
5432        this: Entity<Self>,
5433        buffer: Entity<Buffer>,
5434        peer_id: proto::PeerId,
5435        cx: &mut AsyncApp,
5436    ) -> Result<proto::OpenBufferResponse> {
5437        this.update(cx, |this, cx| {
5438            let is_private = buffer
5439                .read(cx)
5440                .file()
5441                .map(|f| f.is_private())
5442                .unwrap_or_default();
5443            anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
5444            Ok(proto::OpenBufferResponse {
5445                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
5446            })
5447        })
5448    }
5449
5450    fn create_buffer_for_peer(
5451        &mut self,
5452        buffer: &Entity<Buffer>,
5453        peer_id: proto::PeerId,
5454        cx: &mut App,
5455    ) -> BufferId {
5456        self.buffer_store
5457            .update(cx, |buffer_store, cx| {
5458                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
5459            })
5460            .detach_and_log_err(cx);
5461        buffer.read(cx).remote_id()
5462    }
5463
5464    async fn handle_create_image_for_peer(
5465        this: Entity<Self>,
5466        envelope: TypedEnvelope<proto::CreateImageForPeer>,
5467        mut cx: AsyncApp,
5468    ) -> Result<()> {
5469        this.update(&mut cx, |this, cx| {
5470            this.image_store.update(cx, |image_store, cx| {
5471                image_store.handle_create_image_for_peer(envelope, cx)
5472            })
5473        })
5474    }
5475
5476    async fn handle_create_file_for_peer(
5477        this: Entity<Self>,
5478        envelope: TypedEnvelope<proto::CreateFileForPeer>,
5479        mut cx: AsyncApp,
5480    ) -> Result<()> {
5481        use proto::create_file_for_peer::Variant;
5482        log::debug!("handle_create_file_for_peer: received message");
5483
5484        let downloading_files: Arc<Mutex<HashMap<(WorktreeId, String), DownloadingFile>>> =
5485            this.update(&mut cx, |this, _| this.downloading_files.clone());
5486
5487        match &envelope.payload.variant {
5488            Some(Variant::State(state)) => {
5489                log::debug!(
5490                    "handle_create_file_for_peer: got State: id={}, content_size={}",
5491                    state.id,
5492                    state.content_size
5493                );
5494
5495                // Extract worktree_id and path from the File field
5496                if let Some(ref file) = state.file {
5497                    let worktree_id = WorktreeId::from_proto(file.worktree_id);
5498                    let path = file.path.clone();
5499                    let key = (worktree_id, path);
5500                    log::debug!("handle_create_file_for_peer: looking up key={:?}", key);
5501
5502                    let mut files = downloading_files.lock();
5503                    log::trace!(
5504                        "handle_create_file_for_peer: current downloading_files keys: {:?}",
5505                        files.keys().collect::<Vec<_>>()
5506                    );
5507
5508                    if let Some(file_entry) = files.get_mut(&key) {
5509                        file_entry.total_size = state.content_size;
5510                        file_entry.file_id = Some(state.id);
5511                        log::debug!(
5512                            "handle_create_file_for_peer: updated file entry: total_size={}, file_id={}",
5513                            state.content_size,
5514                            state.id
5515                        );
5516                    } else {
5517                        log::warn!(
5518                            "handle_create_file_for_peer: key={:?} not found in downloading_files",
5519                            key
5520                        );
5521                    }
5522                } else {
5523                    log::warn!("handle_create_file_for_peer: State has no file field");
5524                }
5525            }
5526            Some(Variant::Chunk(chunk)) => {
5527                log::debug!(
5528                    "handle_create_file_for_peer: got Chunk: file_id={}, data_len={}",
5529                    chunk.file_id,
5530                    chunk.data.len()
5531                );
5532
5533                // Extract data while holding the lock, then release it before await
5534                let (key_to_remove, write_info): (
5535                    Option<(WorktreeId, String)>,
5536                    Option<(PathBuf, Vec<u8>)>,
5537                ) = {
5538                    let mut files = downloading_files.lock();
5539                    let mut found_key: Option<(WorktreeId, String)> = None;
5540                    let mut write_data: Option<(PathBuf, Vec<u8>)> = None;
5541
5542                    for (key, file_entry) in files.iter_mut() {
5543                        if file_entry.file_id == Some(chunk.file_id) {
5544                            file_entry.chunks.extend_from_slice(&chunk.data);
5545                            log::debug!(
5546                                "handle_create_file_for_peer: accumulated {} bytes, total_size={}",
5547                                file_entry.chunks.len(),
5548                                file_entry.total_size
5549                            );
5550
5551                            if file_entry.chunks.len() as u64 >= file_entry.total_size
5552                                && file_entry.total_size > 0
5553                            {
5554                                let destination = file_entry.destination_path.clone();
5555                                let content = std::mem::take(&mut file_entry.chunks);
5556                                found_key = Some(key.clone());
5557                                write_data = Some((destination, content));
5558                            }
5559                            break;
5560                        }
5561                    }
5562                    (found_key, write_data)
5563                }; // MutexGuard is dropped here
5564
5565                // Perform the async write outside the lock
5566                if let Some((destination, content)) = write_info {
5567                    log::debug!(
5568                        "handle_create_file_for_peer: writing {} bytes to {:?}",
5569                        content.len(),
5570                        destination
5571                    );
5572                    match smol::fs::write(&destination, &content).await {
5573                        Ok(_) => log::info!(
5574                            "handle_create_file_for_peer: successfully wrote file to {:?}",
5575                            destination
5576                        ),
5577                        Err(e) => log::error!(
5578                            "handle_create_file_for_peer: failed to write file: {:?}",
5579                            e
5580                        ),
5581                    }
5582                }
5583
5584                // Remove the completed entry
5585                if let Some(key) = key_to_remove {
5586                    downloading_files.lock().remove(&key);
5587                    log::debug!("handle_create_file_for_peer: removed completed download entry");
5588                }
5589            }
5590            None => {
5591                log::warn!("handle_create_file_for_peer: got None variant");
5592            }
5593        }
5594
5595        Ok(())
5596    }
5597
5598    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
5599        let project_id = match self.client_state {
5600            ProjectClientState::Remote {
5601                sharing_has_stopped,
5602                remote_id,
5603                ..
5604            } => {
5605                if sharing_has_stopped {
5606                    return Task::ready(Err(anyhow!(
5607                        "can't synchronize remote buffers on a readonly project"
5608                    )));
5609                } else {
5610                    remote_id
5611                }
5612            }
5613            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
5614                return Task::ready(Err(anyhow!(
5615                    "can't synchronize remote buffers on a local project"
5616                )));
5617            }
5618        };
5619
5620        let client = self.collab_client.clone();
5621        cx.spawn(async move |this, cx| {
5622            let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
5623                this.buffer_store.read(cx).buffer_version_info(cx)
5624            })?;
5625            let response = client
5626                .request(proto::SynchronizeBuffers {
5627                    project_id,
5628                    buffers,
5629                })
5630                .await?;
5631
5632            let send_updates_for_buffers = this.update(cx, |this, cx| {
5633                response
5634                    .buffers
5635                    .into_iter()
5636                    .map(|buffer| {
5637                        let client = client.clone();
5638                        let buffer_id = match BufferId::new(buffer.id) {
5639                            Ok(id) => id,
5640                            Err(e) => {
5641                                return Task::ready(Err(e));
5642                            }
5643                        };
5644                        let remote_version = language::proto::deserialize_version(&buffer.version);
5645                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5646                            let operations =
5647                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
5648                            cx.background_spawn(async move {
5649                                let operations = operations.await;
5650                                for chunk in split_operations(operations) {
5651                                    client
5652                                        .request(proto::UpdateBuffer {
5653                                            project_id,
5654                                            buffer_id: buffer_id.into(),
5655                                            operations: chunk,
5656                                        })
5657                                        .await?;
5658                                }
5659                                anyhow::Ok(())
5660                            })
5661                        } else {
5662                            Task::ready(Ok(()))
5663                        }
5664                    })
5665                    .collect::<Vec<_>>()
5666            })?;
5667
5668            // Any incomplete buffers have open requests waiting. Request that the host sends
5669            // creates these buffers for us again to unblock any waiting futures.
5670            for id in incomplete_buffer_ids {
5671                cx.background_spawn(client.request(proto::OpenBufferById {
5672                    project_id,
5673                    id: id.into(),
5674                }))
5675                .detach();
5676            }
5677
5678            futures::future::join_all(send_updates_for_buffers)
5679                .await
5680                .into_iter()
5681                .collect()
5682        })
5683    }
5684
5685    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
5686        self.worktree_store.read(cx).worktree_metadata_protos(cx)
5687    }
5688
5689    /// Iterator of all open buffers that have unsaved changes
5690    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
5691        self.buffer_store.read(cx).buffers().filter_map(|buf| {
5692            let buf = buf.read(cx);
5693            if buf.is_dirty() {
5694                buf.project_path(cx)
5695            } else {
5696                None
5697            }
5698        })
5699    }
5700
5701    fn set_worktrees_from_proto(
5702        &mut self,
5703        worktrees: Vec<proto::WorktreeMetadata>,
5704        cx: &mut Context<Project>,
5705    ) -> Result<()> {
5706        self.worktree_store.update(cx, |worktree_store, cx| {
5707            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
5708        })
5709    }
5710
5711    fn set_collaborators_from_proto(
5712        &mut self,
5713        messages: Vec<proto::Collaborator>,
5714        cx: &mut Context<Self>,
5715    ) -> Result<()> {
5716        let mut collaborators = HashMap::default();
5717        for message in messages {
5718            let collaborator = Collaborator::from_proto(message)?;
5719            collaborators.insert(collaborator.peer_id, collaborator);
5720        }
5721        for old_peer_id in self.collaborators.keys() {
5722            if !collaborators.contains_key(old_peer_id) {
5723                cx.emit(Event::CollaboratorLeft(*old_peer_id));
5724            }
5725        }
5726        self.collaborators = collaborators;
5727        Ok(())
5728    }
5729
5730    pub fn supplementary_language_servers<'a>(
5731        &'a self,
5732        cx: &'a App,
5733    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
5734        self.lsp_store.read(cx).supplementary_language_servers()
5735    }
5736
5737    pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
5738        let Some(language) = buffer.language().cloned() else {
5739            return false;
5740        };
5741        self.lsp_store.update(cx, |lsp_store, _| {
5742            let relevant_language_servers = lsp_store
5743                .languages
5744                .lsp_adapters(&language.name())
5745                .into_iter()
5746                .map(|lsp_adapter| lsp_adapter.name())
5747                .collect::<HashSet<_>>();
5748            lsp_store
5749                .language_server_statuses()
5750                .filter_map(|(server_id, server_status)| {
5751                    relevant_language_servers
5752                        .contains(&server_status.name)
5753                        .then_some(server_id)
5754                })
5755                .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5756                .any(InlayHints::check_capabilities)
5757        })
5758    }
5759
5760    pub fn any_language_server_supports_semantic_tokens(
5761        &self,
5762        buffer: &Buffer,
5763        cx: &mut App,
5764    ) -> bool {
5765        let Some(language) = buffer.language().cloned() else {
5766            return false;
5767        };
5768        let lsp_store = self.lsp_store.read(cx);
5769        let relevant_language_servers = lsp_store
5770            .languages
5771            .lsp_adapters(&language.name())
5772            .into_iter()
5773            .map(|lsp_adapter| lsp_adapter.name())
5774            .collect::<HashSet<_>>();
5775        lsp_store
5776            .language_server_statuses()
5777            .filter_map(|(server_id, server_status)| {
5778                relevant_language_servers
5779                    .contains(&server_status.name)
5780                    .then_some(server_id)
5781            })
5782            .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5783            .any(|capabilities| capabilities.semantic_tokens_provider.is_some())
5784    }
5785
5786    pub fn language_server_id_for_name(
5787        &self,
5788        buffer: &Buffer,
5789        name: &LanguageServerName,
5790        cx: &App,
5791    ) -> Option<LanguageServerId> {
5792        let language = buffer.language()?;
5793        let relevant_language_servers = self
5794            .languages
5795            .lsp_adapters(&language.name())
5796            .into_iter()
5797            .map(|lsp_adapter| lsp_adapter.name())
5798            .collect::<HashSet<_>>();
5799        if !relevant_language_servers.contains(name) {
5800            return None;
5801        }
5802        self.language_server_statuses(cx)
5803            .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
5804            .find_map(|(server_id, server_status)| {
5805                if &server_status.name == name {
5806                    Some(server_id)
5807                } else {
5808                    None
5809                }
5810            })
5811    }
5812
5813    #[cfg(feature = "test-support")]
5814    pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
5815        self.lsp_store.update(cx, |this, cx| {
5816            this.running_language_servers_for_local_buffer(buffer, cx)
5817                .next()
5818                .is_some()
5819        })
5820    }
5821
5822    pub fn git_init(
5823        &self,
5824        path: Arc<Path>,
5825        fallback_branch_name: String,
5826        cx: &App,
5827    ) -> Task<Result<()>> {
5828        self.git_store
5829            .read(cx)
5830            .git_init(path, fallback_branch_name, cx)
5831    }
5832
5833    pub fn buffer_store(&self) -> &Entity<BufferStore> {
5834        &self.buffer_store
5835    }
5836
5837    pub fn git_store(&self) -> &Entity<GitStore> {
5838        &self.git_store
5839    }
5840
5841    pub fn agent_server_store(&self) -> &Entity<AgentServerStore> {
5842        &self.agent_server_store
5843    }
5844
5845    #[cfg(feature = "test-support")]
5846    pub fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
5847        use futures::future::join_all;
5848        cx.spawn(async move |this, cx| {
5849            let scans_complete = this
5850                .read_with(cx, |this, cx| {
5851                    this.worktrees(cx)
5852                        .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
5853                        .collect::<Vec<_>>()
5854                })
5855                .unwrap();
5856            join_all(scans_complete).await;
5857            let barriers = this
5858                .update(cx, |this, cx| {
5859                    let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
5860                    repos
5861                        .into_iter()
5862                        .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
5863                        .collect::<Vec<_>>()
5864                })
5865                .unwrap();
5866            join_all(barriers).await;
5867        })
5868    }
5869
5870    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
5871        self.git_store.read(cx).active_repository()
5872    }
5873
5874    pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
5875        self.git_store.read(cx).repositories()
5876    }
5877
5878    pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
5879        self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
5880    }
5881
5882    pub fn set_agent_location(
5883        &mut self,
5884        new_location: Option<AgentLocation>,
5885        cx: &mut Context<Self>,
5886    ) {
5887        if let Some(old_location) = self.agent_location.as_ref() {
5888            old_location
5889                .buffer
5890                .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
5891                .ok();
5892        }
5893
5894        if let Some(location) = new_location.as_ref() {
5895            location
5896                .buffer
5897                .update(cx, |buffer, cx| {
5898                    buffer.set_agent_selections(
5899                        Arc::from([language::Selection {
5900                            id: 0,
5901                            start: location.position,
5902                            end: location.position,
5903                            reversed: false,
5904                            goal: language::SelectionGoal::None,
5905                        }]),
5906                        false,
5907                        CursorShape::Hollow,
5908                        cx,
5909                    )
5910                })
5911                .ok();
5912        }
5913
5914        self.agent_location = new_location;
5915        cx.emit(Event::AgentLocationChanged);
5916    }
5917
5918    pub fn agent_location(&self) -> Option<AgentLocation> {
5919        self.agent_location.clone()
5920    }
5921
5922    pub fn path_style(&self, cx: &App) -> PathStyle {
5923        self.worktree_store.read(cx).path_style()
5924    }
5925
5926    pub fn contains_local_settings_file(
5927        &self,
5928        worktree_id: WorktreeId,
5929        rel_path: &RelPath,
5930        cx: &App,
5931    ) -> bool {
5932        self.worktree_for_id(worktree_id, cx)
5933            .map_or(false, |worktree| {
5934                worktree.read(cx).entry_for_path(rel_path).is_some()
5935            })
5936    }
5937}
5938
5939pub struct PathMatchCandidateSet {
5940    pub snapshot: Snapshot,
5941    pub include_ignored: bool,
5942    pub include_root_name: bool,
5943    pub candidates: Candidates,
5944}
5945
5946pub enum Candidates {
5947    /// Only consider directories.
5948    Directories,
5949    /// Only consider files.
5950    Files,
5951    /// Consider directories and files.
5952    Entries,
5953}
5954
5955impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5956    type Candidates = PathMatchCandidateSetIter<'a>;
5957
5958    fn id(&self) -> usize {
5959        self.snapshot.id().to_usize()
5960    }
5961
5962    fn len(&self) -> usize {
5963        match self.candidates {
5964            Candidates::Files => {
5965                if self.include_ignored {
5966                    self.snapshot.file_count()
5967                } else {
5968                    self.snapshot.visible_file_count()
5969                }
5970            }
5971
5972            Candidates::Directories => {
5973                if self.include_ignored {
5974                    self.snapshot.dir_count()
5975                } else {
5976                    self.snapshot.visible_dir_count()
5977                }
5978            }
5979
5980            Candidates::Entries => {
5981                if self.include_ignored {
5982                    self.snapshot.entry_count()
5983                } else {
5984                    self.snapshot.visible_entry_count()
5985                }
5986            }
5987        }
5988    }
5989
5990    fn prefix(&self) -> Arc<RelPath> {
5991        if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
5992            self.snapshot.root_name().into()
5993        } else {
5994            RelPath::empty().into()
5995        }
5996    }
5997
5998    fn root_is_file(&self) -> bool {
5999        self.snapshot.root_entry().is_some_and(|f| f.is_file())
6000    }
6001
6002    fn path_style(&self) -> PathStyle {
6003        self.snapshot.path_style()
6004    }
6005
6006    fn candidates(&'a self, start: usize) -> Self::Candidates {
6007        PathMatchCandidateSetIter {
6008            traversal: match self.candidates {
6009                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
6010                Candidates::Files => self.snapshot.files(self.include_ignored, start),
6011                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
6012            },
6013        }
6014    }
6015}
6016
6017pub struct PathMatchCandidateSetIter<'a> {
6018    traversal: Traversal<'a>,
6019}
6020
6021impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6022    type Item = fuzzy::PathMatchCandidate<'a>;
6023
6024    fn next(&mut self) -> Option<Self::Item> {
6025        self.traversal
6026            .next()
6027            .map(|entry| fuzzy::PathMatchCandidate {
6028                is_dir: entry.kind.is_dir(),
6029                path: &entry.path,
6030                char_bag: entry.char_bag,
6031            })
6032    }
6033}
6034
6035impl EventEmitter<Event> for Project {}
6036
6037impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
6038    fn from(val: &'a ProjectPath) -> Self {
6039        SettingsLocation {
6040            worktree_id: val.worktree_id,
6041            path: val.path.as_ref(),
6042        }
6043    }
6044}
6045
6046impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
6047    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6048        Self {
6049            worktree_id,
6050            path: path.into(),
6051        }
6052    }
6053}
6054
6055/// ResolvedPath is a path that has been resolved to either a ProjectPath
6056/// or an AbsPath and that *exists*.
6057#[derive(Debug, Clone)]
6058pub enum ResolvedPath {
6059    ProjectPath {
6060        project_path: ProjectPath,
6061        is_dir: bool,
6062    },
6063    AbsPath {
6064        path: String,
6065        is_dir: bool,
6066    },
6067}
6068
6069impl ResolvedPath {
6070    pub fn abs_path(&self) -> Option<&str> {
6071        match self {
6072            Self::AbsPath { path, .. } => Some(path),
6073            _ => None,
6074        }
6075    }
6076
6077    pub fn into_abs_path(self) -> Option<String> {
6078        match self {
6079            Self::AbsPath { path, .. } => Some(path),
6080            _ => None,
6081        }
6082    }
6083
6084    pub fn project_path(&self) -> Option<&ProjectPath> {
6085        match self {
6086            Self::ProjectPath { project_path, .. } => Some(project_path),
6087            _ => None,
6088        }
6089    }
6090
6091    pub fn is_file(&self) -> bool {
6092        !self.is_dir()
6093    }
6094
6095    pub fn is_dir(&self) -> bool {
6096        match self {
6097            Self::ProjectPath { is_dir, .. } => *is_dir,
6098            Self::AbsPath { is_dir, .. } => *is_dir,
6099        }
6100    }
6101}
6102
6103impl ProjectItem for Buffer {
6104    fn try_open(
6105        project: &Entity<Project>,
6106        path: &ProjectPath,
6107        cx: &mut App,
6108    ) -> Option<Task<Result<Entity<Self>>>> {
6109        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
6110    }
6111
6112    fn entry_id(&self, _cx: &App) -> Option<ProjectEntryId> {
6113        File::from_dyn(self.file()).and_then(|file| file.project_entry_id())
6114    }
6115
6116    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
6117        let file = self.file()?;
6118
6119        (!matches!(file.disk_state(), DiskState::Historic { .. })).then(|| ProjectPath {
6120            worktree_id: file.worktree_id(cx),
6121            path: file.path().clone(),
6122        })
6123    }
6124
6125    fn is_dirty(&self) -> bool {
6126        self.is_dirty()
6127    }
6128}
6129
6130impl Completion {
6131    pub fn kind(&self) -> Option<CompletionItemKind> {
6132        self.source
6133            // `lsp::CompletionListItemDefaults` has no `kind` field
6134            .lsp_completion(false)
6135            .and_then(|lsp_completion| lsp_completion.kind)
6136    }
6137
6138    pub fn label(&self) -> Option<String> {
6139        self.source
6140            .lsp_completion(false)
6141            .map(|lsp_completion| lsp_completion.label.clone())
6142    }
6143
6144    /// A key that can be used to sort completions when displaying
6145    /// them to the user.
6146    pub fn sort_key(&self) -> (usize, &str) {
6147        const DEFAULT_KIND_KEY: usize = 4;
6148        let kind_key = self
6149            .kind()
6150            .and_then(|lsp_completion_kind| match lsp_completion_kind {
6151                lsp::CompletionItemKind::KEYWORD => Some(0),
6152                lsp::CompletionItemKind::VARIABLE => Some(1),
6153                lsp::CompletionItemKind::CONSTANT => Some(2),
6154                lsp::CompletionItemKind::PROPERTY => Some(3),
6155                _ => None,
6156            })
6157            .unwrap_or(DEFAULT_KIND_KEY);
6158        (kind_key, self.label.filter_text())
6159    }
6160
6161    /// Whether this completion is a snippet.
6162    pub fn is_snippet_kind(&self) -> bool {
6163        matches!(
6164            &self.source,
6165            CompletionSource::Lsp { lsp_completion, .. }
6166            if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
6167        )
6168    }
6169
6170    /// Whether this completion is a snippet or snippet-style LSP completion.
6171    pub fn is_snippet(&self) -> bool {
6172        self.source
6173            // `lsp::CompletionListItemDefaults` has `insert_text_format` field
6174            .lsp_completion(true)
6175            .is_some_and(|lsp_completion| {
6176                lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
6177            })
6178    }
6179
6180    /// Returns the corresponding color for this completion.
6181    ///
6182    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
6183    pub fn color(&self) -> Option<Hsla> {
6184        // `lsp::CompletionListItemDefaults` has no `kind` field
6185        let lsp_completion = self.source.lsp_completion(false)?;
6186        if lsp_completion.kind? == CompletionItemKind::COLOR {
6187            return color_extractor::extract_color(&lsp_completion);
6188        }
6189        None
6190    }
6191}
6192
6193fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
6194    match level {
6195        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
6196        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
6197        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
6198    }
6199}
6200
6201fn provide_inline_values(
6202    captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
6203    snapshot: &language::BufferSnapshot,
6204    max_row: usize,
6205) -> Vec<InlineValueLocation> {
6206    let mut variables = Vec::new();
6207    let mut variable_position = HashSet::default();
6208    let mut scopes = Vec::new();
6209
6210    let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
6211
6212    for (capture_range, capture_kind) in captures {
6213        match capture_kind {
6214            language::DebuggerTextObject::Variable => {
6215                let variable_name = snapshot
6216                    .text_for_range(capture_range.clone())
6217                    .collect::<String>();
6218                let point = snapshot.offset_to_point(capture_range.end);
6219
6220                while scopes
6221                    .last()
6222                    .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
6223                {
6224                    scopes.pop();
6225                }
6226
6227                if point.row as usize > max_row {
6228                    break;
6229                }
6230
6231                let scope = if scopes
6232                    .last()
6233                    .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
6234                {
6235                    VariableScope::Global
6236                } else {
6237                    VariableScope::Local
6238                };
6239
6240                if variable_position.insert(capture_range.end) {
6241                    variables.push(InlineValueLocation {
6242                        variable_name,
6243                        scope,
6244                        lookup: VariableLookupKind::Variable,
6245                        row: point.row as usize,
6246                        column: point.column as usize,
6247                    });
6248                }
6249            }
6250            language::DebuggerTextObject::Scope => {
6251                while scopes.last().map_or_else(
6252                    || false,
6253                    |scope: &Range<usize>| {
6254                        !(scope.contains(&capture_range.start)
6255                            && scope.contains(&capture_range.end))
6256                    },
6257                ) {
6258                    scopes.pop();
6259                }
6260                scopes.push(capture_range);
6261            }
6262        }
6263    }
6264
6265    variables
6266}