project.rs

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