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