project.rs

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