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