project.rs

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