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