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