project.rs

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