project.rs

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