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