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