project.rs

   1pub mod buffer_store;
   2mod color_extractor;
   3pub mod connection_manager;
   4pub mod debounced_delay;
   5pub mod git;
   6pub mod image_store;
   7pub mod lsp_command;
   8pub mod lsp_ext_command;
   9pub mod lsp_store;
  10pub mod prettier_store;
  11pub mod project_settings;
  12mod project_tree;
  13pub mod search;
  14mod task_inventory;
  15pub mod task_store;
  16pub mod terminals;
  17pub mod toolchain_store;
  18pub mod worktree_store;
  19
  20#[cfg(test)]
  21mod project_tests;
  22
  23mod direnv;
  24mod environment;
  25use buffer_diff::BufferDiff;
  26pub use environment::EnvironmentErrorMessage;
  27use git::Repository;
  28pub mod search_history;
  29mod yarn;
  30
  31use crate::git::GitStore;
  32use anyhow::{anyhow, Context as _, Result};
  33use buffer_store::{BufferStore, BufferStoreEvent};
  34use client::{
  35    proto, Client, Collaborator, PendingEntitySubscription, ProjectId, TypedEnvelope, UserStore,
  36};
  37use clock::ReplicaId;
  38use collections::{BTreeSet, HashMap, HashSet};
  39use debounced_delay::DebouncedDelay;
  40pub use environment::ProjectEnvironment;
  41use futures::{
  42    channel::mpsc::{self, UnboundedReceiver},
  43    future::try_join_all,
  44    StreamExt,
  45};
  46pub use image_store::{ImageItem, ImageStore};
  47use image_store::{ImageItemEvent, ImageStoreEvent};
  48
  49use ::git::{
  50    blame::Blame,
  51    repository::{Branch, GitRepository, RepoPath},
  52    status::FileStatus,
  53};
  54use gpui::{
  55    AnyEntity, App, AppContext as _, AsyncApp, BorrowAppContext, Context, Entity, EventEmitter,
  56    Hsla, SharedString, Task, WeakEntity, Window,
  57};
  58use itertools::Itertools;
  59use language::{
  60    language_settings::InlayHintKind, proto::split_operations, Buffer, BufferEvent, Capability,
  61    CodeLabel, CompletionDocumentation, File as _, Language, LanguageName, LanguageRegistry,
  62    PointUtf16, ToOffset, ToPointUtf16, Toolchain, ToolchainList, Transaction, Unclipped,
  63};
  64use lsp::{
  65    CodeActionKind, CompletionContext, CompletionItemKind, DocumentHighlightKind, LanguageServerId,
  66    LanguageServerName, MessageActionItem,
  67};
  68use lsp_command::*;
  69use lsp_store::{LspFormatTarget, OpenLspBufferHandle};
  70use node_runtime::NodeRuntime;
  71use parking_lot::Mutex;
  72pub use prettier_store::PrettierStore;
  73use project_settings::{ProjectSettings, SettingsObserver, SettingsObserverEvent};
  74use remote::{SshConnectionOptions, SshRemoteClient};
  75use rpc::{
  76    proto::{FromProto, LanguageServerPromptResponse, ToProto, SSH_PROJECT_ID},
  77    AnyProtoClient, ErrorCode,
  78};
  79use search::{SearchInputKind, SearchQuery, SearchResult};
  80use search_history::SearchHistory;
  81use settings::{InvalidSettingsError, Settings, SettingsLocation, SettingsStore};
  82use smol::channel::Receiver;
  83use snippet::Snippet;
  84use snippet_provider::SnippetProvider;
  85use std::{
  86    borrow::Cow,
  87    ops::Range,
  88    path::{Component, Path, PathBuf},
  89    pin::pin,
  90    str,
  91    sync::Arc,
  92    time::Duration,
  93};
  94use task_store::TaskStore;
  95use terminals::Terminals;
  96use text::{Anchor, BufferId};
  97use toolchain_store::EmptyToolchainStore;
  98use util::{
  99    paths::{compare_paths, SanitizedPath},
 100    ResultExt as _,
 101};
 102use worktree::{CreatedEntry, Snapshot, Traversal};
 103use worktree_store::{WorktreeStore, WorktreeStoreEvent};
 104
 105pub use fs::*;
 106pub use language::Location;
 107#[cfg(any(test, feature = "test-support"))]
 108pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
 109pub use task_inventory::{
 110    BasicContextProvider, ContextProviderWithTasks, Inventory, TaskSourceKind,
 111};
 112pub use worktree::{
 113    Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId, UpdatedEntriesSet,
 114    UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings, FS_WATCH_LATENCY,
 115};
 116
 117pub use buffer_store::ProjectTransaction;
 118pub use lsp_store::{
 119    DiagnosticSummary, LanguageServerLogType, LanguageServerProgress, LanguageServerPromptRequest,
 120    LanguageServerStatus, LanguageServerToQuery, LspStore, LspStoreEvent,
 121    SERVER_PROGRESS_THROTTLE_TIMEOUT,
 122};
 123pub use toolchain_store::ToolchainStore;
 124const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
 125const MAX_SEARCH_RESULT_FILES: usize = 5_000;
 126const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
 127
 128pub trait ProjectItem {
 129    fn try_open(
 130        project: &Entity<Project>,
 131        path: &ProjectPath,
 132        cx: &mut App,
 133    ) -> Option<Task<Result<Entity<Self>>>>
 134    where
 135        Self: Sized;
 136    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId>;
 137    fn project_path(&self, cx: &App) -> Option<ProjectPath>;
 138    fn is_dirty(&self) -> bool;
 139}
 140
 141#[derive(Clone)]
 142pub enum OpenedBufferEvent {
 143    Disconnected,
 144    Ok(BufferId),
 145    Err(BufferId, Arc<anyhow::Error>),
 146}
 147
 148/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
 149/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
 150/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
 151///
 152/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
 153pub struct Project {
 154    active_entry: Option<ProjectEntryId>,
 155    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
 156    languages: Arc<LanguageRegistry>,
 157    client: Arc<client::Client>,
 158    join_project_response_message_id: u32,
 159    task_store: Entity<TaskStore>,
 160    user_store: Entity<UserStore>,
 161    fs: Arc<dyn Fs>,
 162    ssh_client: Option<Entity<SshRemoteClient>>,
 163    client_state: ProjectClientState,
 164    git_store: Entity<GitStore>,
 165    collaborators: HashMap<proto::PeerId, Collaborator>,
 166    client_subscriptions: Vec<client::Subscription>,
 167    worktree_store: Entity<WorktreeStore>,
 168    buffer_store: Entity<BufferStore>,
 169    image_store: Entity<ImageStore>,
 170    lsp_store: Entity<LspStore>,
 171    _subscriptions: Vec<gpui::Subscription>,
 172    buffers_needing_diff: HashSet<WeakEntity<Buffer>>,
 173    git_diff_debouncer: DebouncedDelay<Self>,
 174    remotely_created_models: Arc<Mutex<RemotelyCreatedModels>>,
 175    terminals: Terminals,
 176    node: Option<NodeRuntime>,
 177    search_history: SearchHistory,
 178    search_included_history: SearchHistory,
 179    search_excluded_history: SearchHistory,
 180    snippets: Entity<SnippetProvider>,
 181    environment: Entity<ProjectEnvironment>,
 182    settings_observer: Entity<SettingsObserver>,
 183    toolchain_store: Option<Entity<ToolchainStore>>,
 184}
 185
 186#[derive(Default)]
 187struct RemotelyCreatedModels {
 188    worktrees: Vec<Entity<Worktree>>,
 189    buffers: Vec<Entity<Buffer>>,
 190    retain_count: usize,
 191}
 192
 193struct RemotelyCreatedModelGuard {
 194    remote_models: std::sync::Weak<Mutex<RemotelyCreatedModels>>,
 195}
 196
 197impl Drop for RemotelyCreatedModelGuard {
 198    fn drop(&mut self) {
 199        if let Some(remote_models) = self.remote_models.upgrade() {
 200            let mut remote_models = remote_models.lock();
 201            assert!(
 202                remote_models.retain_count > 0,
 203                "RemotelyCreatedModelGuard dropped too many times"
 204            );
 205            remote_models.retain_count -= 1;
 206            if remote_models.retain_count == 0 {
 207                remote_models.buffers.clear();
 208                remote_models.worktrees.clear();
 209            }
 210        }
 211    }
 212}
 213/// Message ordered with respect to buffer operations
 214#[derive(Debug)]
 215enum BufferOrderedMessage {
 216    Operation {
 217        buffer_id: BufferId,
 218        operation: proto::Operation,
 219    },
 220    LanguageServerUpdate {
 221        language_server_id: LanguageServerId,
 222        message: proto::update_language_server::Variant,
 223    },
 224    Resync,
 225}
 226
 227#[derive(Debug)]
 228enum ProjectClientState {
 229    /// Single-player mode.
 230    Local,
 231    /// Multi-player mode but still a local project.
 232    Shared { remote_id: u64 },
 233    /// Multi-player mode but working on a remote project.
 234    Remote {
 235        sharing_has_stopped: bool,
 236        capability: Capability,
 237        remote_id: u64,
 238        replica_id: ReplicaId,
 239    },
 240}
 241
 242#[derive(Clone, Debug, PartialEq)]
 243pub enum Event {
 244    LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
 245    LanguageServerRemoved(LanguageServerId),
 246    LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
 247    Toast {
 248        notification_id: SharedString,
 249        message: String,
 250    },
 251    HideToast {
 252        notification_id: SharedString,
 253    },
 254    LanguageServerPrompt(LanguageServerPromptRequest),
 255    LanguageNotFound(Entity<Buffer>),
 256    ActiveEntryChanged(Option<ProjectEntryId>),
 257    ActivateProjectPanel,
 258    WorktreeAdded(WorktreeId),
 259    WorktreeOrderChanged,
 260    WorktreeRemoved(WorktreeId),
 261    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
 262    WorktreeUpdatedGitRepositories(WorktreeId),
 263    DiskBasedDiagnosticsStarted {
 264        language_server_id: LanguageServerId,
 265    },
 266    DiskBasedDiagnosticsFinished {
 267        language_server_id: LanguageServerId,
 268    },
 269    DiagnosticsUpdated {
 270        path: ProjectPath,
 271        language_server_id: LanguageServerId,
 272    },
 273    RemoteIdChanged(Option<u64>),
 274    DisconnectedFromHost,
 275    DisconnectedFromSshRemote,
 276    Closed,
 277    DeletedEntry(WorktreeId, ProjectEntryId),
 278    CollaboratorUpdated {
 279        old_peer_id: proto::PeerId,
 280        new_peer_id: proto::PeerId,
 281    },
 282    CollaboratorJoined(proto::PeerId),
 283    CollaboratorLeft(proto::PeerId),
 284    HostReshared,
 285    Reshared,
 286    Rejoined,
 287    RefreshInlayHints,
 288    RevealInProjectPanel(ProjectEntryId),
 289    SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
 290    ExpandedAllForEntry(WorktreeId, ProjectEntryId),
 291}
 292
 293#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 294pub struct ProjectPath {
 295    pub worktree_id: WorktreeId,
 296    pub path: Arc<Path>,
 297}
 298
 299impl ProjectPath {
 300    pub fn from_proto(p: proto::ProjectPath) -> Self {
 301        Self {
 302            worktree_id: WorktreeId::from_proto(p.worktree_id),
 303            path: Arc::<Path>::from_proto(p.path),
 304        }
 305    }
 306
 307    pub fn to_proto(&self) -> proto::ProjectPath {
 308        proto::ProjectPath {
 309            worktree_id: self.worktree_id.to_proto(),
 310            path: self.path.as_ref().to_proto(),
 311        }
 312    }
 313
 314    pub fn root_path(worktree_id: WorktreeId) -> Self {
 315        Self {
 316            worktree_id,
 317            path: Path::new("").into(),
 318        }
 319    }
 320}
 321
 322#[derive(Debug, Default)]
 323pub enum PrepareRenameResponse {
 324    Success(Range<Anchor>),
 325    OnlyUnpreparedRenameSupported,
 326    #[default]
 327    InvalidPosition,
 328}
 329
 330#[derive(Debug, Clone, PartialEq, Eq)]
 331pub struct InlayHint {
 332    pub position: language::Anchor,
 333    pub label: InlayHintLabel,
 334    pub kind: Option<InlayHintKind>,
 335    pub padding_left: bool,
 336    pub padding_right: bool,
 337    pub tooltip: Option<InlayHintTooltip>,
 338    pub resolve_state: ResolveState,
 339}
 340
 341/// The user's intent behind a given completion confirmation
 342#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
 343pub enum CompletionIntent {
 344    /// The user intends to 'commit' this result, if possible
 345    /// completion confirmations should run side effects
 346    Complete,
 347    /// The user intends to continue 'composing' this completion
 348    /// completion confirmations should not run side effects and
 349    /// let the user continue composing their action
 350    Compose,
 351}
 352
 353impl CompletionIntent {
 354    pub fn is_complete(&self) -> bool {
 355        self == &Self::Complete
 356    }
 357
 358    pub fn is_compose(&self) -> bool {
 359        self == &Self::Compose
 360    }
 361}
 362
 363/// A completion provided by a language server
 364#[derive(Clone)]
 365pub struct Completion {
 366    /// The range of the buffer that will be replaced.
 367    pub old_range: Range<Anchor>,
 368    /// The new text that will be inserted.
 369    pub new_text: String,
 370    /// A label for this completion that is shown in the menu.
 371    pub label: CodeLabel,
 372    /// The id of the language server that produced this completion.
 373    pub server_id: LanguageServerId,
 374    /// The documentation for this completion.
 375    pub documentation: Option<CompletionDocumentation>,
 376    /// The raw completion provided by the language server.
 377    pub lsp_completion: lsp::CompletionItem,
 378    /// Whether this completion has been resolved, to ensure it happens once per completion.
 379    pub resolved: bool,
 380    /// An optional callback to invoke when this completion is confirmed.
 381    /// Returns, whether new completions should be retriggered after the current one.
 382    /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
 383    /// if no confirmation is provided or `false` is returned, the completion will be committed.
 384    pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut Window, &mut App) -> bool>>,
 385}
 386
 387impl std::fmt::Debug for Completion {
 388    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 389        f.debug_struct("Completion")
 390            .field("old_range", &self.old_range)
 391            .field("new_text", &self.new_text)
 392            .field("label", &self.label)
 393            .field("server_id", &self.server_id)
 394            .field("documentation", &self.documentation)
 395            .field("lsp_completion", &self.lsp_completion)
 396            .finish()
 397    }
 398}
 399
 400/// A completion provided by a language server
 401#[derive(Clone, Debug)]
 402pub(crate) struct CoreCompletion {
 403    old_range: Range<Anchor>,
 404    new_text: String,
 405    server_id: LanguageServerId,
 406    lsp_completion: lsp::CompletionItem,
 407    resolved: bool,
 408}
 409
 410/// A code action provided by a language server.
 411#[derive(Clone, Debug)]
 412pub struct CodeAction {
 413    /// The id of the language server that produced this code action.
 414    pub server_id: LanguageServerId,
 415    /// The range of the buffer where this code action is applicable.
 416    pub range: Range<Anchor>,
 417    /// The raw code action provided by the language server.
 418    pub lsp_action: lsp::CodeAction,
 419}
 420
 421#[derive(Debug, Clone, PartialEq, Eq)]
 422pub enum ResolveState {
 423    Resolved,
 424    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
 425    Resolving,
 426}
 427
 428impl InlayHint {
 429    pub fn text(&self) -> String {
 430        match &self.label {
 431            InlayHintLabel::String(s) => s.to_owned(),
 432            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
 433        }
 434    }
 435}
 436
 437#[derive(Debug, Clone, PartialEq, Eq)]
 438pub enum InlayHintLabel {
 439    String(String),
 440    LabelParts(Vec<InlayHintLabelPart>),
 441}
 442
 443#[derive(Debug, Clone, PartialEq, Eq)]
 444pub struct InlayHintLabelPart {
 445    pub value: String,
 446    pub tooltip: Option<InlayHintLabelPartTooltip>,
 447    pub location: Option<(LanguageServerId, lsp::Location)>,
 448}
 449
 450#[derive(Debug, Clone, PartialEq, Eq)]
 451pub enum InlayHintTooltip {
 452    String(String),
 453    MarkupContent(MarkupContent),
 454}
 455
 456#[derive(Debug, Clone, PartialEq, Eq)]
 457pub enum InlayHintLabelPartTooltip {
 458    String(String),
 459    MarkupContent(MarkupContent),
 460}
 461
 462#[derive(Debug, Clone, PartialEq, Eq)]
 463pub struct MarkupContent {
 464    pub kind: HoverBlockKind,
 465    pub value: String,
 466}
 467
 468#[derive(Debug, Clone)]
 469pub struct LocationLink {
 470    pub origin: Option<Location>,
 471    pub target: Location,
 472}
 473
 474#[derive(Debug)]
 475pub struct DocumentHighlight {
 476    pub range: Range<language::Anchor>,
 477    pub kind: DocumentHighlightKind,
 478}
 479
 480#[derive(Clone, Debug)]
 481pub struct Symbol {
 482    pub language_server_name: LanguageServerName,
 483    pub source_worktree_id: WorktreeId,
 484    pub source_language_server_id: LanguageServerId,
 485    pub path: ProjectPath,
 486    pub label: CodeLabel,
 487    pub name: String,
 488    pub kind: lsp::SymbolKind,
 489    pub range: Range<Unclipped<PointUtf16>>,
 490    pub signature: [u8; 32],
 491}
 492
 493#[derive(Clone, Debug, PartialEq)]
 494pub struct HoverBlock {
 495    pub text: String,
 496    pub kind: HoverBlockKind,
 497}
 498
 499#[derive(Clone, Debug, PartialEq, Eq)]
 500pub enum HoverBlockKind {
 501    PlainText,
 502    Markdown,
 503    Code { language: String },
 504}
 505
 506#[derive(Debug, Clone)]
 507pub struct Hover {
 508    pub contents: Vec<HoverBlock>,
 509    pub range: Option<Range<language::Anchor>>,
 510    pub language: Option<Arc<Language>>,
 511}
 512
 513impl Hover {
 514    pub fn is_empty(&self) -> bool {
 515        self.contents.iter().all(|block| block.text.is_empty())
 516    }
 517}
 518
 519enum EntitySubscription {
 520    Project(PendingEntitySubscription<Project>),
 521    BufferStore(PendingEntitySubscription<BufferStore>),
 522    WorktreeStore(PendingEntitySubscription<WorktreeStore>),
 523    LspStore(PendingEntitySubscription<LspStore>),
 524    SettingsObserver(PendingEntitySubscription<SettingsObserver>),
 525}
 526
 527#[derive(Clone)]
 528pub enum DirectoryLister {
 529    Project(Entity<Project>),
 530    Local(Arc<dyn Fs>),
 531}
 532
 533impl DirectoryLister {
 534    pub fn is_local(&self, cx: &App) -> bool {
 535        match self {
 536            DirectoryLister::Local(_) => true,
 537            DirectoryLister::Project(project) => project.read(cx).is_local(),
 538        }
 539    }
 540
 541    pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &App) -> Cow<'a, str> {
 542        if self.is_local(cx) {
 543            shellexpand::tilde(path)
 544        } else {
 545            Cow::from(path)
 546        }
 547    }
 548
 549    pub fn default_query(&self, cx: &mut App) -> String {
 550        if let DirectoryLister::Project(project) = self {
 551            if let Some(worktree) = project.read(cx).visible_worktrees(cx).next() {
 552                return worktree.read(cx).abs_path().to_string_lossy().to_string();
 553            }
 554        };
 555        "~/".to_string()
 556    }
 557
 558    pub fn list_directory(&self, path: String, cx: &mut App) -> Task<Result<Vec<PathBuf>>> {
 559        match self {
 560            DirectoryLister::Project(project) => {
 561                project.update(cx, |project, cx| project.list_directory(path, cx))
 562            }
 563            DirectoryLister::Local(fs) => {
 564                let fs = fs.clone();
 565                cx.background_executor().spawn(async move {
 566                    let mut results = vec![];
 567                    let expanded = shellexpand::tilde(&path);
 568                    let query = Path::new(expanded.as_ref());
 569                    let mut response = fs.read_dir(query).await?;
 570                    while let Some(path) = response.next().await {
 571                        if let Some(file_name) = path?.file_name() {
 572                            results.push(PathBuf::from(file_name.to_os_string()));
 573                        }
 574                    }
 575                    Ok(results)
 576                })
 577            }
 578        }
 579    }
 580}
 581
 582#[cfg(any(test, feature = "test-support"))]
 583pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
 584    trigger_kind: lsp::CompletionTriggerKind::INVOKED,
 585    trigger_character: None,
 586};
 587
 588impl Project {
 589    pub fn init_settings(cx: &mut App) {
 590        WorktreeSettings::register(cx);
 591        ProjectSettings::register(cx);
 592    }
 593
 594    pub fn init(client: &Arc<Client>, cx: &mut App) {
 595        connection_manager::init(client.clone(), cx);
 596        Self::init_settings(cx);
 597
 598        let client: AnyProtoClient = client.clone().into();
 599        client.add_entity_message_handler(Self::handle_add_collaborator);
 600        client.add_entity_message_handler(Self::handle_update_project_collaborator);
 601        client.add_entity_message_handler(Self::handle_remove_collaborator);
 602        client.add_entity_message_handler(Self::handle_update_project);
 603        client.add_entity_message_handler(Self::handle_unshare_project);
 604        client.add_entity_request_handler(Self::handle_update_buffer);
 605        client.add_entity_message_handler(Self::handle_update_worktree);
 606        client.add_entity_request_handler(Self::handle_synchronize_buffers);
 607
 608        client.add_entity_request_handler(Self::handle_search_candidate_buffers);
 609        client.add_entity_request_handler(Self::handle_open_buffer_by_id);
 610        client.add_entity_request_handler(Self::handle_open_buffer_by_path);
 611        client.add_entity_request_handler(Self::handle_open_new_buffer);
 612        client.add_entity_message_handler(Self::handle_create_buffer_for_peer);
 613
 614        WorktreeStore::init(&client);
 615        BufferStore::init(&client);
 616        LspStore::init(&client);
 617        GitStore::init(&client);
 618        SettingsObserver::init(&client);
 619        TaskStore::init(Some(&client));
 620        ToolchainStore::init(&client);
 621    }
 622
 623    pub fn local(
 624        client: Arc<Client>,
 625        node: NodeRuntime,
 626        user_store: Entity<UserStore>,
 627        languages: Arc<LanguageRegistry>,
 628        fs: Arc<dyn Fs>,
 629        env: Option<HashMap<String, String>>,
 630        cx: &mut App,
 631    ) -> Entity<Self> {
 632        cx.new(|cx: &mut Context<Self>| {
 633            let (tx, rx) = mpsc::unbounded();
 634            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 635                .detach();
 636            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
 637            let worktree_store = cx.new(|_| WorktreeStore::local(false, fs.clone()));
 638            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
 639                .detach();
 640
 641            let buffer_store = cx.new(|cx| BufferStore::local(worktree_store.clone(), cx));
 642            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
 643                .detach();
 644
 645            let image_store = cx.new(|cx| ImageStore::local(worktree_store.clone(), cx));
 646            cx.subscribe(&image_store, Self::on_image_store_event)
 647                .detach();
 648
 649            let prettier_store = cx.new(|cx| {
 650                PrettierStore::new(
 651                    node.clone(),
 652                    fs.clone(),
 653                    languages.clone(),
 654                    worktree_store.clone(),
 655                    cx,
 656                )
 657            });
 658
 659            let environment = ProjectEnvironment::new(&worktree_store, env, cx);
 660            let toolchain_store = cx.new(|cx| {
 661                ToolchainStore::local(
 662                    languages.clone(),
 663                    worktree_store.clone(),
 664                    environment.clone(),
 665                    cx,
 666                )
 667            });
 668            let task_store = cx.new(|cx| {
 669                TaskStore::local(
 670                    fs.clone(),
 671                    buffer_store.downgrade(),
 672                    worktree_store.clone(),
 673                    toolchain_store.read(cx).as_language_toolchain_store(),
 674                    environment.clone(),
 675                    cx,
 676                )
 677            });
 678
 679            let settings_observer = cx.new(|cx| {
 680                SettingsObserver::new_local(
 681                    fs.clone(),
 682                    worktree_store.clone(),
 683                    task_store.clone(),
 684                    cx,
 685                )
 686            });
 687            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
 688                .detach();
 689
 690            let lsp_store = cx.new(|cx| {
 691                LspStore::new_local(
 692                    buffer_store.clone(),
 693                    worktree_store.clone(),
 694                    prettier_store.clone(),
 695                    toolchain_store.clone(),
 696                    environment.clone(),
 697                    languages.clone(),
 698                    client.http_client(),
 699                    fs.clone(),
 700                    cx,
 701                )
 702            });
 703
 704            let git_store =
 705                cx.new(|cx| GitStore::new(&worktree_store, buffer_store.clone(), None, None, cx));
 706
 707            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
 708
 709            Self {
 710                buffer_ordered_messages_tx: tx,
 711                collaborators: Default::default(),
 712                worktree_store,
 713                buffer_store,
 714                image_store,
 715                lsp_store,
 716                join_project_response_message_id: 0,
 717                client_state: ProjectClientState::Local,
 718                git_store,
 719                client_subscriptions: Vec::new(),
 720                _subscriptions: vec![cx.on_release(Self::release)],
 721                active_entry: None,
 722                snippets,
 723                languages,
 724                client,
 725                task_store,
 726                user_store,
 727                settings_observer,
 728                fs,
 729                ssh_client: None,
 730                buffers_needing_diff: Default::default(),
 731                git_diff_debouncer: DebouncedDelay::new(),
 732                terminals: Terminals {
 733                    local_handles: Vec::new(),
 734                },
 735                node: Some(node),
 736                search_history: Self::new_search_history(),
 737                environment,
 738                remotely_created_models: Default::default(),
 739
 740                search_included_history: Self::new_search_history(),
 741                search_excluded_history: Self::new_search_history(),
 742
 743                toolchain_store: Some(toolchain_store),
 744            }
 745        })
 746    }
 747
 748    pub fn ssh(
 749        ssh: Entity<SshRemoteClient>,
 750        client: Arc<Client>,
 751        node: NodeRuntime,
 752        user_store: Entity<UserStore>,
 753        languages: Arc<LanguageRegistry>,
 754        fs: Arc<dyn Fs>,
 755        cx: &mut App,
 756    ) -> Entity<Self> {
 757        cx.new(|cx: &mut Context<Self>| {
 758            let (tx, rx) = mpsc::unbounded();
 759            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 760                .detach();
 761            let global_snippets_dir = paths::config_dir().join("snippets");
 762            let snippets =
 763                SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
 764
 765            let ssh_proto = ssh.read(cx).proto_client();
 766            let worktree_store =
 767                cx.new(|_| WorktreeStore::remote(false, ssh_proto.clone(), SSH_PROJECT_ID));
 768            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
 769                .detach();
 770
 771            let buffer_store = cx.new(|cx| {
 772                BufferStore::remote(
 773                    worktree_store.clone(),
 774                    ssh.read(cx).proto_client(),
 775                    SSH_PROJECT_ID,
 776                    cx,
 777                )
 778            });
 779            let image_store = cx.new(|cx| {
 780                ImageStore::remote(
 781                    worktree_store.clone(),
 782                    ssh.read(cx).proto_client(),
 783                    SSH_PROJECT_ID,
 784                    cx,
 785                )
 786            });
 787            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
 788                .detach();
 789            let toolchain_store = cx
 790                .new(|cx| ToolchainStore::remote(SSH_PROJECT_ID, ssh.read(cx).proto_client(), cx));
 791            let task_store = cx.new(|cx| {
 792                TaskStore::remote(
 793                    fs.clone(),
 794                    buffer_store.downgrade(),
 795                    worktree_store.clone(),
 796                    toolchain_store.read(cx).as_language_toolchain_store(),
 797                    ssh.read(cx).proto_client(),
 798                    SSH_PROJECT_ID,
 799                    cx,
 800                )
 801            });
 802
 803            let settings_observer = cx.new(|cx| {
 804                SettingsObserver::new_remote(worktree_store.clone(), task_store.clone(), cx)
 805            });
 806            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
 807                .detach();
 808
 809            let environment = ProjectEnvironment::new(&worktree_store, None, cx);
 810
 811            let lsp_store = cx.new(|cx| {
 812                LspStore::new_remote(
 813                    buffer_store.clone(),
 814                    worktree_store.clone(),
 815                    Some(toolchain_store.clone()),
 816                    languages.clone(),
 817                    ssh_proto.clone(),
 818                    SSH_PROJECT_ID,
 819                    fs.clone(),
 820                    cx,
 821                )
 822            });
 823            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
 824
 825            let git_store = cx.new(|cx| {
 826                GitStore::new(
 827                    &worktree_store,
 828                    buffer_store.clone(),
 829                    Some(ssh_proto.clone()),
 830                    Some(ProjectId(SSH_PROJECT_ID)),
 831                    cx,
 832                )
 833            });
 834
 835            cx.subscribe(&ssh, Self::on_ssh_event).detach();
 836            cx.observe(&ssh, |_, _, cx| cx.notify()).detach();
 837
 838            let this = Self {
 839                buffer_ordered_messages_tx: tx,
 840                collaborators: Default::default(),
 841                worktree_store,
 842                buffer_store,
 843                image_store,
 844                lsp_store,
 845                join_project_response_message_id: 0,
 846                client_state: ProjectClientState::Local,
 847                git_store,
 848                client_subscriptions: Vec::new(),
 849                _subscriptions: vec![
 850                    cx.on_release(Self::release),
 851                    cx.on_app_quit(|this, cx| {
 852                        let shutdown = this.ssh_client.take().and_then(|client| {
 853                            client
 854                                .read(cx)
 855                                .shutdown_processes(Some(proto::ShutdownRemoteServer {}))
 856                        });
 857
 858                        cx.background_executor().spawn(async move {
 859                            if let Some(shutdown) = shutdown {
 860                                shutdown.await;
 861                            }
 862                        })
 863                    }),
 864                ],
 865                active_entry: None,
 866                snippets,
 867                languages,
 868                client,
 869                task_store,
 870                user_store,
 871                settings_observer,
 872                fs,
 873                ssh_client: Some(ssh.clone()),
 874                buffers_needing_diff: Default::default(),
 875                git_diff_debouncer: DebouncedDelay::new(),
 876                terminals: Terminals {
 877                    local_handles: Vec::new(),
 878                },
 879                node: Some(node),
 880                search_history: Self::new_search_history(),
 881                environment,
 882                remotely_created_models: Default::default(),
 883
 884                search_included_history: Self::new_search_history(),
 885                search_excluded_history: Self::new_search_history(),
 886
 887                toolchain_store: Some(toolchain_store),
 888            };
 889
 890            // ssh -> local machine handlers
 891            let ssh = ssh.read(cx);
 892            ssh.subscribe_to_entity(SSH_PROJECT_ID, &cx.entity());
 893            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.buffer_store);
 894            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.worktree_store);
 895            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.lsp_store);
 896            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.settings_observer);
 897            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.git_store);
 898
 899            ssh_proto.add_entity_message_handler(Self::handle_create_buffer_for_peer);
 900            ssh_proto.add_entity_message_handler(Self::handle_update_worktree);
 901            ssh_proto.add_entity_message_handler(Self::handle_update_project);
 902            ssh_proto.add_entity_message_handler(Self::handle_toast);
 903            ssh_proto.add_entity_request_handler(Self::handle_language_server_prompt_request);
 904            ssh_proto.add_entity_message_handler(Self::handle_hide_toast);
 905            ssh_proto.add_entity_request_handler(Self::handle_update_buffer_from_ssh);
 906            BufferStore::init(&ssh_proto);
 907            LspStore::init(&ssh_proto);
 908            SettingsObserver::init(&ssh_proto);
 909            TaskStore::init(Some(&ssh_proto));
 910            ToolchainStore::init(&ssh_proto);
 911            GitStore::init(&ssh_proto);
 912
 913            this
 914        })
 915    }
 916
 917    pub async fn remote(
 918        remote_id: u64,
 919        client: Arc<Client>,
 920        user_store: Entity<UserStore>,
 921        languages: Arc<LanguageRegistry>,
 922        fs: Arc<dyn Fs>,
 923        cx: AsyncApp,
 924    ) -> Result<Entity<Self>> {
 925        let project =
 926            Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
 927        cx.update(|cx| {
 928            connection_manager::Manager::global(cx).update(cx, |manager, cx| {
 929                manager.maintain_project_connection(&project, cx)
 930            })
 931        })?;
 932        Ok(project)
 933    }
 934
 935    pub async fn in_room(
 936        remote_id: u64,
 937        client: Arc<Client>,
 938        user_store: Entity<UserStore>,
 939        languages: Arc<LanguageRegistry>,
 940        fs: Arc<dyn Fs>,
 941        cx: AsyncApp,
 942    ) -> Result<Entity<Self>> {
 943        client.authenticate_and_connect(true, &cx).await?;
 944
 945        let subscriptions = [
 946            EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
 947            EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
 948            EntitySubscription::WorktreeStore(
 949                client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
 950            ),
 951            EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
 952            EntitySubscription::SettingsObserver(
 953                client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
 954            ),
 955        ];
 956        let response = client
 957            .request_envelope(proto::JoinProject {
 958                project_id: remote_id,
 959            })
 960            .await?;
 961        Self::from_join_project_response(
 962            response,
 963            subscriptions,
 964            client,
 965            false,
 966            user_store,
 967            languages,
 968            fs,
 969            cx,
 970        )
 971        .await
 972    }
 973
 974    #[allow(clippy::too_many_arguments)]
 975    async fn from_join_project_response(
 976        response: TypedEnvelope<proto::JoinProjectResponse>,
 977        subscriptions: [EntitySubscription; 5],
 978        client: Arc<Client>,
 979        run_tasks: bool,
 980        user_store: Entity<UserStore>,
 981        languages: Arc<LanguageRegistry>,
 982        fs: Arc<dyn Fs>,
 983        mut cx: AsyncApp,
 984    ) -> Result<Entity<Self>> {
 985        let remote_id = response.payload.project_id;
 986        let role = response.payload.role();
 987
 988        let worktree_store = cx.new(|_| {
 989            WorktreeStore::remote(true, client.clone().into(), response.payload.project_id)
 990        })?;
 991        let buffer_store = cx.new(|cx| {
 992            BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
 993        })?;
 994        let image_store = cx.new(|cx| {
 995            ImageStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
 996        })?;
 997
 998        let lsp_store = cx.new(|cx| {
 999            let mut lsp_store = LspStore::new_remote(
1000                buffer_store.clone(),
1001                worktree_store.clone(),
1002                None,
1003                languages.clone(),
1004                client.clone().into(),
1005                remote_id,
1006                fs.clone(),
1007                cx,
1008            );
1009            lsp_store.set_language_server_statuses_from_proto(response.payload.language_servers);
1010            lsp_store
1011        })?;
1012
1013        let task_store = cx.new(|cx| {
1014            if run_tasks {
1015                TaskStore::remote(
1016                    fs.clone(),
1017                    buffer_store.downgrade(),
1018                    worktree_store.clone(),
1019                    Arc::new(EmptyToolchainStore),
1020                    client.clone().into(),
1021                    remote_id,
1022                    cx,
1023                )
1024            } else {
1025                TaskStore::Noop
1026            }
1027        })?;
1028
1029        let settings_observer = cx.new(|cx| {
1030            SettingsObserver::new_remote(worktree_store.clone(), task_store.clone(), cx)
1031        })?;
1032
1033        let git_store = cx.new(|cx| {
1034            GitStore::new(
1035                &worktree_store,
1036                buffer_store.clone(),
1037                Some(client.clone().into()),
1038                Some(ProjectId(remote_id)),
1039                cx,
1040            )
1041        })?;
1042
1043        let this = cx.new(|cx| {
1044            let replica_id = response.payload.replica_id as ReplicaId;
1045
1046            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1047
1048            let mut worktrees = Vec::new();
1049            for worktree in response.payload.worktrees {
1050                let worktree =
1051                    Worktree::remote(remote_id, replica_id, worktree, client.clone().into(), cx);
1052                worktrees.push(worktree);
1053            }
1054
1055            let (tx, rx) = mpsc::unbounded();
1056            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
1057                .detach();
1058
1059            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1060                .detach();
1061
1062            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1063                .detach();
1064            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1065            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1066                .detach();
1067
1068            let mut this = Self {
1069                buffer_ordered_messages_tx: tx,
1070                buffer_store: buffer_store.clone(),
1071                image_store,
1072                worktree_store: worktree_store.clone(),
1073                lsp_store: lsp_store.clone(),
1074                active_entry: None,
1075                collaborators: Default::default(),
1076                join_project_response_message_id: response.message_id,
1077                languages,
1078                user_store: user_store.clone(),
1079                task_store,
1080                snippets,
1081                fs,
1082                ssh_client: None,
1083                settings_observer: settings_observer.clone(),
1084                client_subscriptions: Default::default(),
1085                _subscriptions: vec![cx.on_release(Self::release)],
1086                client: client.clone(),
1087                client_state: ProjectClientState::Remote {
1088                    sharing_has_stopped: false,
1089                    capability: Capability::ReadWrite,
1090                    remote_id,
1091                    replica_id,
1092                },
1093                git_store,
1094                buffers_needing_diff: Default::default(),
1095                git_diff_debouncer: DebouncedDelay::new(),
1096                terminals: Terminals {
1097                    local_handles: Vec::new(),
1098                },
1099                node: None,
1100                search_history: Self::new_search_history(),
1101                search_included_history: Self::new_search_history(),
1102                search_excluded_history: Self::new_search_history(),
1103                environment: ProjectEnvironment::new(&worktree_store, None, cx),
1104                remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1105                toolchain_store: None,
1106            };
1107            this.set_role(role, cx);
1108            for worktree in worktrees {
1109                this.add_worktree(&worktree, cx);
1110            }
1111            this
1112        })?;
1113
1114        let subscriptions = subscriptions
1115            .into_iter()
1116            .map(|s| match s {
1117                EntitySubscription::BufferStore(subscription) => {
1118                    subscription.set_entity(&buffer_store, &mut cx)
1119                }
1120                EntitySubscription::WorktreeStore(subscription) => {
1121                    subscription.set_entity(&worktree_store, &mut cx)
1122                }
1123                EntitySubscription::SettingsObserver(subscription) => {
1124                    subscription.set_entity(&settings_observer, &mut cx)
1125                }
1126                EntitySubscription::Project(subscription) => {
1127                    subscription.set_entity(&this, &mut cx)
1128                }
1129                EntitySubscription::LspStore(subscription) => {
1130                    subscription.set_entity(&lsp_store, &mut cx)
1131                }
1132            })
1133            .collect::<Vec<_>>();
1134
1135        let user_ids = response
1136            .payload
1137            .collaborators
1138            .iter()
1139            .map(|peer| peer.user_id)
1140            .collect();
1141        user_store
1142            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
1143            .await?;
1144
1145        this.update(&mut cx, |this, cx| {
1146            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1147            this.client_subscriptions.extend(subscriptions);
1148            anyhow::Ok(())
1149        })??;
1150
1151        Ok(this)
1152    }
1153
1154    fn new_search_history() -> SearchHistory {
1155        SearchHistory::new(
1156            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1157            search_history::QueryInsertionBehavior::AlwaysInsert,
1158        )
1159    }
1160
1161    fn release(&mut self, cx: &mut App) {
1162        if let Some(client) = self.ssh_client.take() {
1163            let shutdown = client
1164                .read(cx)
1165                .shutdown_processes(Some(proto::ShutdownRemoteServer {}));
1166
1167            cx.background_executor()
1168                .spawn(async move {
1169                    if let Some(shutdown) = shutdown {
1170                        shutdown.await;
1171                    }
1172                })
1173                .detach()
1174        }
1175
1176        match &self.client_state {
1177            ProjectClientState::Local => {}
1178            ProjectClientState::Shared { .. } => {
1179                let _ = self.unshare_internal(cx);
1180            }
1181            ProjectClientState::Remote { remote_id, .. } => {
1182                let _ = self.client.send(proto::LeaveProject {
1183                    project_id: *remote_id,
1184                });
1185                self.disconnected_from_host_internal(cx);
1186            }
1187        }
1188    }
1189
1190    #[cfg(any(test, feature = "test-support"))]
1191    pub async fn example(
1192        root_paths: impl IntoIterator<Item = &Path>,
1193        cx: &mut AsyncApp,
1194    ) -> Entity<Project> {
1195        use clock::FakeSystemClock;
1196
1197        let fs = Arc::new(RealFs::default());
1198        let languages = LanguageRegistry::test(cx.background_executor().clone());
1199        let clock = Arc::new(FakeSystemClock::new());
1200        let http_client = http_client::FakeHttpClient::with_404_response();
1201        let client = cx
1202            .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1203            .unwrap();
1204        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx)).unwrap();
1205        let project = cx
1206            .update(|cx| {
1207                Project::local(
1208                    client,
1209                    node_runtime::NodeRuntime::unavailable(),
1210                    user_store,
1211                    Arc::new(languages),
1212                    fs,
1213                    None,
1214                    cx,
1215                )
1216            })
1217            .unwrap();
1218        for path in root_paths {
1219            let (tree, _) = project
1220                .update(cx, |project, cx| {
1221                    project.find_or_create_worktree(path, true, cx)
1222                })
1223                .unwrap()
1224                .await
1225                .unwrap();
1226            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1227                .unwrap()
1228                .await;
1229        }
1230        project
1231    }
1232
1233    #[cfg(any(test, feature = "test-support"))]
1234    pub async fn test(
1235        fs: Arc<dyn Fs>,
1236        root_paths: impl IntoIterator<Item = &Path>,
1237        cx: &mut gpui::TestAppContext,
1238    ) -> Entity<Project> {
1239        use clock::FakeSystemClock;
1240
1241        let languages = LanguageRegistry::test(cx.executor());
1242        let clock = Arc::new(FakeSystemClock::new());
1243        let http_client = http_client::FakeHttpClient::with_404_response();
1244        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1245        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1246        let project = cx.update(|cx| {
1247            Project::local(
1248                client,
1249                node_runtime::NodeRuntime::unavailable(),
1250                user_store,
1251                Arc::new(languages),
1252                fs,
1253                None,
1254                cx,
1255            )
1256        });
1257        for path in root_paths {
1258            let (tree, _) = project
1259                .update(cx, |project, cx| {
1260                    project.find_or_create_worktree(path, true, cx)
1261                })
1262                .await
1263                .unwrap();
1264
1265            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1266                .await;
1267        }
1268        project
1269    }
1270
1271    pub fn lsp_store(&self) -> Entity<LspStore> {
1272        self.lsp_store.clone()
1273    }
1274
1275    pub fn worktree_store(&self) -> Entity<WorktreeStore> {
1276        self.worktree_store.clone()
1277    }
1278
1279    pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
1280        self.buffer_store.read(cx).get(remote_id)
1281    }
1282
1283    pub fn languages(&self) -> &Arc<LanguageRegistry> {
1284        &self.languages
1285    }
1286
1287    pub fn client(&self) -> Arc<Client> {
1288        self.client.clone()
1289    }
1290
1291    pub fn ssh_client(&self) -> Option<Entity<SshRemoteClient>> {
1292        self.ssh_client.clone()
1293    }
1294
1295    pub fn user_store(&self) -> Entity<UserStore> {
1296        self.user_store.clone()
1297    }
1298
1299    pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1300        self.node.as_ref()
1301    }
1302
1303    pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
1304        self.buffer_store.read(cx).buffers().collect()
1305    }
1306
1307    pub fn environment(&self) -> &Entity<ProjectEnvironment> {
1308        &self.environment
1309    }
1310
1311    pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
1312        self.environment.read(cx).get_cli_environment()
1313    }
1314
1315    pub fn shell_environment_errors<'a>(
1316        &'a self,
1317        cx: &'a App,
1318    ) -> impl Iterator<Item = (&'a WorktreeId, &'a EnvironmentErrorMessage)> {
1319        self.environment.read(cx).environment_errors()
1320    }
1321
1322    pub fn remove_environment_error(&mut self, cx: &mut Context<Self>, worktree_id: WorktreeId) {
1323        self.environment.update(cx, |environment, _| {
1324            environment.remove_environment_error(worktree_id);
1325        });
1326    }
1327
1328    #[cfg(any(test, feature = "test-support"))]
1329    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
1330        self.buffer_store
1331            .read(cx)
1332            .get_by_path(&path.into(), cx)
1333            .is_some()
1334    }
1335
1336    pub fn fs(&self) -> &Arc<dyn Fs> {
1337        &self.fs
1338    }
1339
1340    pub fn remote_id(&self) -> Option<u64> {
1341        match self.client_state {
1342            ProjectClientState::Local => None,
1343            ProjectClientState::Shared { remote_id, .. }
1344            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1345        }
1346    }
1347
1348    pub fn supports_terminal(&self, _cx: &App) -> bool {
1349        if self.is_local() {
1350            return true;
1351        }
1352        if self.is_via_ssh() {
1353            return true;
1354        }
1355
1356        return false;
1357    }
1358
1359    pub fn ssh_connection_string(&self, cx: &App) -> Option<SharedString> {
1360        if let Some(ssh_state) = &self.ssh_client {
1361            return Some(ssh_state.read(cx).connection_string().into());
1362        }
1363
1364        return None;
1365    }
1366
1367    pub fn ssh_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
1368        self.ssh_client
1369            .as_ref()
1370            .map(|ssh| ssh.read(cx).connection_state())
1371    }
1372
1373    pub fn ssh_connection_options(&self, cx: &App) -> Option<SshConnectionOptions> {
1374        self.ssh_client
1375            .as_ref()
1376            .map(|ssh| ssh.read(cx).connection_options())
1377    }
1378
1379    pub fn replica_id(&self) -> ReplicaId {
1380        match self.client_state {
1381            ProjectClientState::Remote { replica_id, .. } => replica_id,
1382            _ => {
1383                if self.ssh_client.is_some() {
1384                    1
1385                } else {
1386                    0
1387                }
1388            }
1389        }
1390    }
1391
1392    pub fn task_store(&self) -> &Entity<TaskStore> {
1393        &self.task_store
1394    }
1395
1396    pub fn snippets(&self) -> &Entity<SnippetProvider> {
1397        &self.snippets
1398    }
1399
1400    pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1401        match kind {
1402            SearchInputKind::Query => &self.search_history,
1403            SearchInputKind::Include => &self.search_included_history,
1404            SearchInputKind::Exclude => &self.search_excluded_history,
1405        }
1406    }
1407
1408    pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1409        match kind {
1410            SearchInputKind::Query => &mut self.search_history,
1411            SearchInputKind::Include => &mut self.search_included_history,
1412            SearchInputKind::Exclude => &mut self.search_excluded_history,
1413        }
1414    }
1415
1416    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1417        &self.collaborators
1418    }
1419
1420    pub fn host(&self) -> Option<&Collaborator> {
1421        self.collaborators.values().find(|c| c.is_host)
1422    }
1423
1424    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
1425        self.worktree_store.update(cx, |store, _| {
1426            store.set_worktrees_reordered(worktrees_reordered);
1427        });
1428    }
1429
1430    /// Collect all worktrees, including ones that don't appear in the project panel
1431    pub fn worktrees<'a>(
1432        &self,
1433        cx: &'a App,
1434    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1435        self.worktree_store.read(cx).worktrees()
1436    }
1437
1438    /// Collect all user-visible worktrees, the ones that appear in the project panel.
1439    pub fn visible_worktrees<'a>(
1440        &'a self,
1441        cx: &'a App,
1442    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1443        self.worktree_store.read(cx).visible_worktrees(cx)
1444    }
1445
1446    pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
1447        self.visible_worktrees(cx)
1448            .map(|tree| tree.read(cx).root_name())
1449    }
1450
1451    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
1452        self.worktree_store.read(cx).worktree_for_id(id, cx)
1453    }
1454
1455    pub fn worktree_for_entry(
1456        &self,
1457        entry_id: ProjectEntryId,
1458        cx: &App,
1459    ) -> Option<Entity<Worktree>> {
1460        self.worktree_store
1461            .read(cx)
1462            .worktree_for_entry(entry_id, cx)
1463    }
1464
1465    pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
1466        self.worktree_for_entry(entry_id, cx)
1467            .map(|worktree| worktree.read(cx).id())
1468    }
1469
1470    /// Checks if the entry is the root of a worktree.
1471    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
1472        self.worktree_for_entry(entry_id, cx)
1473            .map(|worktree| {
1474                worktree
1475                    .read(cx)
1476                    .root_entry()
1477                    .is_some_and(|e| e.id == entry_id)
1478            })
1479            .unwrap_or(false)
1480    }
1481
1482    pub fn project_path_git_status(
1483        &self,
1484        project_path: &ProjectPath,
1485        cx: &App,
1486    ) -> Option<FileStatus> {
1487        self.worktree_for_id(project_path.worktree_id, cx)
1488            .and_then(|worktree| worktree.read(cx).status_for_file(&project_path.path))
1489    }
1490
1491    pub fn visibility_for_paths(
1492        &self,
1493        paths: &[PathBuf],
1494        metadatas: &[Metadata],
1495        exclude_sub_dirs: bool,
1496        cx: &App,
1497    ) -> Option<bool> {
1498        paths
1499            .iter()
1500            .zip(metadatas)
1501            .map(|(path, metadata)| self.visibility_for_path(path, metadata, exclude_sub_dirs, cx))
1502            .max()
1503            .flatten()
1504    }
1505
1506    pub fn visibility_for_path(
1507        &self,
1508        path: &Path,
1509        metadata: &Metadata,
1510        exclude_sub_dirs: bool,
1511        cx: &App,
1512    ) -> Option<bool> {
1513        let sanitized_path = SanitizedPath::from(path);
1514        let path = sanitized_path.as_path();
1515        self.worktrees(cx)
1516            .filter_map(|worktree| {
1517                let worktree = worktree.read(cx);
1518                let abs_path = worktree.as_local()?.abs_path();
1519                let contains = path == abs_path
1520                    || (path.starts_with(abs_path) && (!exclude_sub_dirs || !metadata.is_dir));
1521                contains.then(|| worktree.is_visible())
1522            })
1523            .max()
1524    }
1525
1526    pub fn create_entry(
1527        &mut self,
1528        project_path: impl Into<ProjectPath>,
1529        is_directory: bool,
1530        cx: &mut Context<Self>,
1531    ) -> Task<Result<CreatedEntry>> {
1532        let project_path = project_path.into();
1533        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1534            return Task::ready(Err(anyhow!(format!(
1535                "No worktree for path {project_path:?}"
1536            ))));
1537        };
1538        worktree.update(cx, |worktree, cx| {
1539            worktree.create_entry(project_path.path, is_directory, cx)
1540        })
1541    }
1542
1543    pub fn copy_entry(
1544        &mut self,
1545        entry_id: ProjectEntryId,
1546        relative_worktree_source_path: Option<PathBuf>,
1547        new_path: impl Into<Arc<Path>>,
1548        cx: &mut Context<Self>,
1549    ) -> Task<Result<Option<Entry>>> {
1550        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1551            return Task::ready(Ok(None));
1552        };
1553        worktree.update(cx, |worktree, cx| {
1554            worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1555        })
1556    }
1557
1558    /// Renames the project entry with given `entry_id`.
1559    ///
1560    /// `new_path` is a relative path to worktree root.
1561    /// If root entry is renamed then its new root name is used instead.
1562    pub fn rename_entry(
1563        &mut self,
1564        entry_id: ProjectEntryId,
1565        new_path: impl Into<Arc<Path>>,
1566        cx: &mut Context<Self>,
1567    ) -> Task<Result<CreatedEntry>> {
1568        let worktree_store = self.worktree_store.read(cx);
1569        let new_path = new_path.into();
1570        let Some((worktree, old_path, is_dir)) = worktree_store
1571            .worktree_and_entry_for_id(entry_id, cx)
1572            .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
1573        else {
1574            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1575        };
1576
1577        let worktree_id = worktree.read(cx).id();
1578        let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
1579
1580        let lsp_store = self.lsp_store().downgrade();
1581        cx.spawn(|_, mut cx| async move {
1582            let (old_abs_path, new_abs_path) = {
1583                let root_path = worktree.update(&mut cx, |this, _| this.abs_path())?;
1584                let new_abs_path = if is_root_entry {
1585                    root_path.parent().unwrap().join(&new_path)
1586                } else {
1587                    root_path.join(&new_path)
1588                };
1589                (root_path.join(&old_path), new_abs_path)
1590            };
1591            LspStore::will_rename_entry(
1592                lsp_store.clone(),
1593                worktree_id,
1594                &old_abs_path,
1595                &new_abs_path,
1596                is_dir,
1597                cx.clone(),
1598            )
1599            .await;
1600
1601            let entry = worktree
1602                .update(&mut cx, |worktree, cx| {
1603                    worktree.rename_entry(entry_id, new_path.clone(), cx)
1604                })?
1605                .await?;
1606
1607            lsp_store
1608                .update(&mut cx, |this, _| {
1609                    this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
1610                })
1611                .ok();
1612            Ok(entry)
1613        })
1614    }
1615
1616    pub fn delete_file(
1617        &mut self,
1618        path: ProjectPath,
1619        trash: bool,
1620        cx: &mut Context<Self>,
1621    ) -> Option<Task<Result<()>>> {
1622        let entry = self.entry_for_path(&path, cx)?;
1623        self.delete_entry(entry.id, trash, cx)
1624    }
1625
1626    pub fn delete_entry(
1627        &mut self,
1628        entry_id: ProjectEntryId,
1629        trash: bool,
1630        cx: &mut Context<Self>,
1631    ) -> Option<Task<Result<()>>> {
1632        let worktree = self.worktree_for_entry(entry_id, cx)?;
1633        cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
1634        worktree.update(cx, |worktree, cx| {
1635            worktree.delete_entry(entry_id, trash, cx)
1636        })
1637    }
1638
1639    pub fn expand_entry(
1640        &mut self,
1641        worktree_id: WorktreeId,
1642        entry_id: ProjectEntryId,
1643        cx: &mut Context<Self>,
1644    ) -> Option<Task<Result<()>>> {
1645        let worktree = self.worktree_for_id(worktree_id, cx)?;
1646        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1647    }
1648
1649    pub fn expand_all_for_entry(
1650        &mut self,
1651        worktree_id: WorktreeId,
1652        entry_id: ProjectEntryId,
1653        cx: &mut Context<Self>,
1654    ) -> Option<Task<Result<()>>> {
1655        let worktree = self.worktree_for_id(worktree_id, cx)?;
1656        let task = worktree.update(cx, |worktree, cx| {
1657            worktree.expand_all_for_entry(entry_id, cx)
1658        });
1659        Some(cx.spawn(|this, mut cx| async move {
1660            task.ok_or_else(|| anyhow!("no task"))?.await?;
1661            this.update(&mut cx, |_, cx| {
1662                cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
1663            })?;
1664            Ok(())
1665        }))
1666    }
1667
1668    pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
1669        if !matches!(self.client_state, ProjectClientState::Local) {
1670            return Err(anyhow!("project was already shared"));
1671        }
1672
1673        self.client_subscriptions.extend([
1674            self.client
1675                .subscribe_to_entity(project_id)?
1676                .set_entity(&cx.entity(), &mut cx.to_async()),
1677            self.client
1678                .subscribe_to_entity(project_id)?
1679                .set_entity(&self.worktree_store, &mut cx.to_async()),
1680            self.client
1681                .subscribe_to_entity(project_id)?
1682                .set_entity(&self.buffer_store, &mut cx.to_async()),
1683            self.client
1684                .subscribe_to_entity(project_id)?
1685                .set_entity(&self.lsp_store, &mut cx.to_async()),
1686            self.client
1687                .subscribe_to_entity(project_id)?
1688                .set_entity(&self.settings_observer, &mut cx.to_async()),
1689            self.client
1690                .subscribe_to_entity(project_id)?
1691                .set_entity(&self.git_store, &mut cx.to_async()),
1692        ]);
1693
1694        self.buffer_store.update(cx, |buffer_store, cx| {
1695            buffer_store.shared(project_id, self.client.clone().into(), cx)
1696        });
1697        self.worktree_store.update(cx, |worktree_store, cx| {
1698            worktree_store.shared(project_id, self.client.clone().into(), cx);
1699        });
1700        self.lsp_store.update(cx, |lsp_store, cx| {
1701            lsp_store.shared(project_id, self.client.clone().into(), cx)
1702        });
1703        self.task_store.update(cx, |task_store, cx| {
1704            task_store.shared(project_id, self.client.clone().into(), cx);
1705        });
1706        self.settings_observer.update(cx, |settings_observer, cx| {
1707            settings_observer.shared(project_id, self.client.clone().into(), cx)
1708        });
1709
1710        self.client_state = ProjectClientState::Shared {
1711            remote_id: project_id,
1712        };
1713
1714        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1715        cx.notify();
1716        Ok(())
1717    }
1718
1719    pub fn reshared(
1720        &mut self,
1721        message: proto::ResharedProject,
1722        cx: &mut Context<Self>,
1723    ) -> Result<()> {
1724        self.buffer_store
1725            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
1726        self.set_collaborators_from_proto(message.collaborators, cx)?;
1727
1728        self.worktree_store.update(cx, |worktree_store, cx| {
1729            worktree_store.send_project_updates(cx);
1730        });
1731        cx.notify();
1732        cx.emit(Event::Reshared);
1733        Ok(())
1734    }
1735
1736    pub fn rejoined(
1737        &mut self,
1738        message: proto::RejoinedProject,
1739        message_id: u32,
1740        cx: &mut Context<Self>,
1741    ) -> Result<()> {
1742        cx.update_global::<SettingsStore, _>(|store, cx| {
1743            self.worktree_store.update(cx, |worktree_store, cx| {
1744                for worktree in worktree_store.worktrees() {
1745                    store
1746                        .clear_local_settings(worktree.read(cx).id(), cx)
1747                        .log_err();
1748                }
1749            });
1750        });
1751
1752        self.join_project_response_message_id = message_id;
1753        self.set_worktrees_from_proto(message.worktrees, cx)?;
1754        self.set_collaborators_from_proto(message.collaborators, cx)?;
1755        self.lsp_store.update(cx, |lsp_store, _| {
1756            lsp_store.set_language_server_statuses_from_proto(message.language_servers)
1757        });
1758        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
1759            .unwrap();
1760        cx.emit(Event::Rejoined);
1761        cx.notify();
1762        Ok(())
1763    }
1764
1765    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
1766        self.unshare_internal(cx)?;
1767        cx.notify();
1768        Ok(())
1769    }
1770
1771    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
1772        if self.is_via_collab() {
1773            return Err(anyhow!("attempted to unshare a remote project"));
1774        }
1775
1776        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
1777            self.client_state = ProjectClientState::Local;
1778            self.collaborators.clear();
1779            self.client_subscriptions.clear();
1780            self.worktree_store.update(cx, |store, cx| {
1781                store.unshared(cx);
1782            });
1783            self.buffer_store.update(cx, |buffer_store, cx| {
1784                buffer_store.forget_shared_buffers();
1785                buffer_store.unshared(cx)
1786            });
1787            self.task_store.update(cx, |task_store, cx| {
1788                task_store.unshared(cx);
1789            });
1790            self.settings_observer.update(cx, |settings_observer, cx| {
1791                settings_observer.unshared(cx);
1792            });
1793
1794            self.client
1795                .send(proto::UnshareProject {
1796                    project_id: remote_id,
1797                })
1798                .ok();
1799            Ok(())
1800        } else {
1801            Err(anyhow!("attempted to unshare an unshared project"))
1802        }
1803    }
1804
1805    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
1806        if self.is_disconnected(cx) {
1807            return;
1808        }
1809        self.disconnected_from_host_internal(cx);
1810        cx.emit(Event::DisconnectedFromHost);
1811        cx.notify();
1812    }
1813
1814    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
1815        let new_capability =
1816            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
1817                Capability::ReadWrite
1818            } else {
1819                Capability::ReadOnly
1820            };
1821        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
1822            if *capability == new_capability {
1823                return;
1824            }
1825
1826            *capability = new_capability;
1827            for buffer in self.opened_buffers(cx) {
1828                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
1829            }
1830        }
1831    }
1832
1833    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
1834        if let ProjectClientState::Remote {
1835            sharing_has_stopped,
1836            ..
1837        } = &mut self.client_state
1838        {
1839            *sharing_has_stopped = true;
1840            self.collaborators.clear();
1841            self.worktree_store.update(cx, |store, cx| {
1842                store.disconnected_from_host(cx);
1843            });
1844            self.buffer_store.update(cx, |buffer_store, cx| {
1845                buffer_store.disconnected_from_host(cx)
1846            });
1847            self.lsp_store
1848                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
1849        }
1850    }
1851
1852    pub fn close(&mut self, cx: &mut Context<Self>) {
1853        cx.emit(Event::Closed);
1854    }
1855
1856    pub fn is_disconnected(&self, cx: &App) -> bool {
1857        match &self.client_state {
1858            ProjectClientState::Remote {
1859                sharing_has_stopped,
1860                ..
1861            } => *sharing_has_stopped,
1862            ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
1863            _ => false,
1864        }
1865    }
1866
1867    fn ssh_is_disconnected(&self, cx: &App) -> bool {
1868        self.ssh_client
1869            .as_ref()
1870            .map(|ssh| ssh.read(cx).is_disconnected())
1871            .unwrap_or(false)
1872    }
1873
1874    pub fn capability(&self) -> Capability {
1875        match &self.client_state {
1876            ProjectClientState::Remote { capability, .. } => *capability,
1877            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
1878        }
1879    }
1880
1881    pub fn is_read_only(&self, cx: &App) -> bool {
1882        self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
1883    }
1884
1885    pub fn is_local(&self) -> bool {
1886        match &self.client_state {
1887            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1888                self.ssh_client.is_none()
1889            }
1890            ProjectClientState::Remote { .. } => false,
1891        }
1892    }
1893
1894    pub fn is_via_ssh(&self) -> bool {
1895        match &self.client_state {
1896            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1897                self.ssh_client.is_some()
1898            }
1899            ProjectClientState::Remote { .. } => false,
1900        }
1901    }
1902
1903    pub fn is_via_collab(&self) -> bool {
1904        match &self.client_state {
1905            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
1906            ProjectClientState::Remote { .. } => true,
1907        }
1908    }
1909
1910    pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
1911        self.buffer_store
1912            .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
1913    }
1914
1915    pub fn create_local_buffer(
1916        &mut self,
1917        text: &str,
1918        language: Option<Arc<Language>>,
1919        cx: &mut Context<Self>,
1920    ) -> Entity<Buffer> {
1921        if self.is_via_collab() || self.is_via_ssh() {
1922            panic!("called create_local_buffer on a remote project")
1923        }
1924        self.buffer_store.update(cx, |buffer_store, cx| {
1925            buffer_store.create_local_buffer(text, language, cx)
1926        })
1927    }
1928
1929    pub fn open_path(
1930        &mut self,
1931        path: ProjectPath,
1932        cx: &mut Context<Self>,
1933    ) -> Task<Result<(Option<ProjectEntryId>, AnyEntity)>> {
1934        let task = self.open_buffer(path.clone(), cx);
1935        cx.spawn(move |_, cx| async move {
1936            let buffer = task.await?;
1937            let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1938                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1939            })?;
1940
1941            let buffer: &AnyEntity = &buffer;
1942            Ok((project_entry_id, buffer.clone()))
1943        })
1944    }
1945
1946    pub fn open_local_buffer(
1947        &mut self,
1948        abs_path: impl AsRef<Path>,
1949        cx: &mut Context<Self>,
1950    ) -> Task<Result<Entity<Buffer>>> {
1951        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1952            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1953        } else {
1954            Task::ready(Err(anyhow!("no such path")))
1955        }
1956    }
1957
1958    #[cfg(any(test, feature = "test-support"))]
1959    pub fn open_local_buffer_with_lsp(
1960        &mut self,
1961        abs_path: impl AsRef<Path>,
1962        cx: &mut Context<Self>,
1963    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
1964        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1965            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
1966        } else {
1967            Task::ready(Err(anyhow!("no such path")))
1968        }
1969    }
1970
1971    pub fn open_buffer(
1972        &mut self,
1973        path: impl Into<ProjectPath>,
1974        cx: &mut App,
1975    ) -> Task<Result<Entity<Buffer>>> {
1976        if self.is_disconnected(cx) {
1977            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1978        }
1979
1980        self.buffer_store.update(cx, |buffer_store, cx| {
1981            buffer_store.open_buffer(path.into(), cx)
1982        })
1983    }
1984
1985    #[cfg(any(test, feature = "test-support"))]
1986    pub fn open_buffer_with_lsp(
1987        &mut self,
1988        path: impl Into<ProjectPath>,
1989        cx: &mut Context<Self>,
1990    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
1991        let buffer = self.open_buffer(path, cx);
1992        cx.spawn(|this, mut cx| async move {
1993            let buffer = buffer.await?;
1994            let handle = this.update(&mut cx, |project, cx| {
1995                project.register_buffer_with_language_servers(&buffer, cx)
1996            })?;
1997            Ok((buffer, handle))
1998        })
1999    }
2000
2001    pub fn register_buffer_with_language_servers(
2002        &self,
2003        buffer: &Entity<Buffer>,
2004        cx: &mut App,
2005    ) -> OpenLspBufferHandle {
2006        self.lsp_store.update(cx, |lsp_store, cx| {
2007            lsp_store.register_buffer_with_language_servers(&buffer, false, cx)
2008        })
2009    }
2010
2011    pub fn open_unstaged_diff(
2012        &mut self,
2013        buffer: Entity<Buffer>,
2014        cx: &mut Context<Self>,
2015    ) -> Task<Result<Entity<BufferDiff>>> {
2016        if self.is_disconnected(cx) {
2017            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2018        }
2019
2020        self.buffer_store.update(cx, |buffer_store, cx| {
2021            buffer_store.open_unstaged_diff(buffer, cx)
2022        })
2023    }
2024
2025    pub fn open_uncommitted_diff(
2026        &mut self,
2027        buffer: Entity<Buffer>,
2028        cx: &mut Context<Self>,
2029    ) -> Task<Result<Entity<BufferDiff>>> {
2030        if self.is_disconnected(cx) {
2031            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2032        }
2033
2034        self.buffer_store.update(cx, |buffer_store, cx| {
2035            buffer_store.open_uncommitted_diff(buffer, cx)
2036        })
2037    }
2038
2039    pub fn open_buffer_by_id(
2040        &mut self,
2041        id: BufferId,
2042        cx: &mut Context<Self>,
2043    ) -> Task<Result<Entity<Buffer>>> {
2044        if let Some(buffer) = self.buffer_for_id(id, cx) {
2045            Task::ready(Ok(buffer))
2046        } else if self.is_local() || self.is_via_ssh() {
2047            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
2048        } else if let Some(project_id) = self.remote_id() {
2049            let request = self.client.request(proto::OpenBufferById {
2050                project_id,
2051                id: id.into(),
2052            });
2053            cx.spawn(move |project, mut cx| async move {
2054                let buffer_id = BufferId::new(request.await?.buffer_id)?;
2055                project
2056                    .update(&mut cx, |project, cx| {
2057                        project.buffer_store.update(cx, |buffer_store, cx| {
2058                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
2059                        })
2060                    })?
2061                    .await
2062            })
2063        } else {
2064            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2065        }
2066    }
2067
2068    pub fn save_buffers(
2069        &self,
2070        buffers: HashSet<Entity<Buffer>>,
2071        cx: &mut Context<Self>,
2072    ) -> Task<Result<()>> {
2073        cx.spawn(move |this, mut cx| async move {
2074            let save_tasks = buffers.into_iter().filter_map(|buffer| {
2075                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
2076                    .ok()
2077            });
2078            try_join_all(save_tasks).await?;
2079            Ok(())
2080        })
2081    }
2082
2083    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2084        self.buffer_store
2085            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2086    }
2087
2088    pub fn save_buffer_as(
2089        &mut self,
2090        buffer: Entity<Buffer>,
2091        path: ProjectPath,
2092        cx: &mut Context<Self>,
2093    ) -> Task<Result<()>> {
2094        self.buffer_store.update(cx, |buffer_store, cx| {
2095            buffer_store.save_buffer_as(buffer.clone(), path, cx)
2096        })
2097    }
2098
2099    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2100        self.buffer_store.read(cx).get_by_path(path, cx)
2101    }
2102
2103    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2104        {
2105            let mut remotely_created_models = self.remotely_created_models.lock();
2106            if remotely_created_models.retain_count > 0 {
2107                remotely_created_models.buffers.push(buffer.clone())
2108            }
2109        }
2110
2111        self.request_buffer_diff_recalculation(buffer, cx);
2112
2113        cx.subscribe(buffer, |this, buffer, event, cx| {
2114            this.on_buffer_event(buffer, event, cx);
2115        })
2116        .detach();
2117
2118        Ok(())
2119    }
2120
2121    pub fn open_image(
2122        &mut self,
2123        path: impl Into<ProjectPath>,
2124        cx: &mut Context<Self>,
2125    ) -> Task<Result<Entity<ImageItem>>> {
2126        if self.is_disconnected(cx) {
2127            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2128        }
2129
2130        let open_image_task = self.image_store.update(cx, |image_store, cx| {
2131            image_store.open_image(path.into(), cx)
2132        });
2133
2134        let weak_project = cx.entity().downgrade();
2135        cx.spawn(move |_, mut cx| async move {
2136            let image_item = open_image_task.await?;
2137            let project = weak_project
2138                .upgrade()
2139                .ok_or_else(|| anyhow!("Project dropped"))?;
2140
2141            let metadata =
2142                ImageItem::load_image_metadata(image_item.clone(), project, &mut cx).await?;
2143            image_item.update(&mut cx, |image_item, cx| {
2144                image_item.image_metadata = Some(metadata);
2145                cx.emit(ImageItemEvent::MetadataUpdated);
2146            })?;
2147
2148            Ok(image_item)
2149        })
2150    }
2151
2152    async fn send_buffer_ordered_messages(
2153        this: WeakEntity<Self>,
2154        rx: UnboundedReceiver<BufferOrderedMessage>,
2155        mut cx: AsyncApp,
2156    ) -> Result<()> {
2157        const MAX_BATCH_SIZE: usize = 128;
2158
2159        let mut operations_by_buffer_id = HashMap::default();
2160        async fn flush_operations(
2161            this: &WeakEntity<Project>,
2162            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2163            needs_resync_with_host: &mut bool,
2164            is_local: bool,
2165            cx: &mut AsyncApp,
2166        ) -> Result<()> {
2167            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2168                let request = this.update(cx, |this, _| {
2169                    let project_id = this.remote_id()?;
2170                    Some(this.client.request(proto::UpdateBuffer {
2171                        buffer_id: buffer_id.into(),
2172                        project_id,
2173                        operations,
2174                    }))
2175                })?;
2176                if let Some(request) = request {
2177                    if request.await.is_err() && !is_local {
2178                        *needs_resync_with_host = true;
2179                        break;
2180                    }
2181                }
2182            }
2183            Ok(())
2184        }
2185
2186        let mut needs_resync_with_host = false;
2187        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2188
2189        while let Some(changes) = changes.next().await {
2190            let is_local = this.update(&mut cx, |this, _| this.is_local())?;
2191
2192            for change in changes {
2193                match change {
2194                    BufferOrderedMessage::Operation {
2195                        buffer_id,
2196                        operation,
2197                    } => {
2198                        if needs_resync_with_host {
2199                            continue;
2200                        }
2201
2202                        operations_by_buffer_id
2203                            .entry(buffer_id)
2204                            .or_insert(Vec::new())
2205                            .push(operation);
2206                    }
2207
2208                    BufferOrderedMessage::Resync => {
2209                        operations_by_buffer_id.clear();
2210                        if this
2211                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2212                            .await
2213                            .is_ok()
2214                        {
2215                            needs_resync_with_host = false;
2216                        }
2217                    }
2218
2219                    BufferOrderedMessage::LanguageServerUpdate {
2220                        language_server_id,
2221                        message,
2222                    } => {
2223                        flush_operations(
2224                            &this,
2225                            &mut operations_by_buffer_id,
2226                            &mut needs_resync_with_host,
2227                            is_local,
2228                            &mut cx,
2229                        )
2230                        .await?;
2231
2232                        this.update(&mut cx, |this, _| {
2233                            if let Some(project_id) = this.remote_id() {
2234                                this.client
2235                                    .send(proto::UpdateLanguageServer {
2236                                        project_id,
2237                                        language_server_id: language_server_id.0 as u64,
2238                                        variant: Some(message),
2239                                    })
2240                                    .log_err();
2241                            }
2242                        })?;
2243                    }
2244                }
2245            }
2246
2247            flush_operations(
2248                &this,
2249                &mut operations_by_buffer_id,
2250                &mut needs_resync_with_host,
2251                is_local,
2252                &mut cx,
2253            )
2254            .await?;
2255        }
2256
2257        Ok(())
2258    }
2259
2260    fn on_buffer_store_event(
2261        &mut self,
2262        _: Entity<BufferStore>,
2263        event: &BufferStoreEvent,
2264        cx: &mut Context<Self>,
2265    ) {
2266        match event {
2267            BufferStoreEvent::BufferAdded(buffer) => {
2268                self.register_buffer(buffer, cx).log_err();
2269            }
2270            BufferStoreEvent::BufferChangedFilePath { .. } => {}
2271            BufferStoreEvent::BufferDropped(buffer_id) => {
2272                if let Some(ref ssh_client) = self.ssh_client {
2273                    ssh_client
2274                        .read(cx)
2275                        .proto_client()
2276                        .send(proto::CloseBuffer {
2277                            project_id: 0,
2278                            buffer_id: buffer_id.to_proto(),
2279                        })
2280                        .log_err();
2281                }
2282            }
2283        }
2284    }
2285
2286    fn on_image_store_event(
2287        &mut self,
2288        _: Entity<ImageStore>,
2289        event: &ImageStoreEvent,
2290        cx: &mut Context<Self>,
2291    ) {
2292        match event {
2293            ImageStoreEvent::ImageAdded(image) => {
2294                cx.subscribe(image, |this, image, event, cx| {
2295                    this.on_image_event(image, event, cx);
2296                })
2297                .detach();
2298            }
2299        }
2300    }
2301
2302    fn on_lsp_store_event(
2303        &mut self,
2304        _: Entity<LspStore>,
2305        event: &LspStoreEvent,
2306        cx: &mut Context<Self>,
2307    ) {
2308        match event {
2309            LspStoreEvent::DiagnosticsUpdated {
2310                language_server_id,
2311                path,
2312            } => cx.emit(Event::DiagnosticsUpdated {
2313                path: path.clone(),
2314                language_server_id: *language_server_id,
2315            }),
2316            LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2317                Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2318            ),
2319            LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2320                cx.emit(Event::LanguageServerRemoved(*language_server_id))
2321            }
2322            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2323                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2324            ),
2325            LspStoreEvent::LanguageDetected {
2326                buffer,
2327                new_language,
2328            } => {
2329                let Some(_) = new_language else {
2330                    cx.emit(Event::LanguageNotFound(buffer.clone()));
2331                    return;
2332                };
2333            }
2334            LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2335            LspStoreEvent::LanguageServerPrompt(prompt) => {
2336                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2337            }
2338            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2339                cx.emit(Event::DiskBasedDiagnosticsStarted {
2340                    language_server_id: *language_server_id,
2341                });
2342            }
2343            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2344                cx.emit(Event::DiskBasedDiagnosticsFinished {
2345                    language_server_id: *language_server_id,
2346                });
2347            }
2348            LspStoreEvent::LanguageServerUpdate {
2349                language_server_id,
2350                message,
2351            } => {
2352                if self.is_local() {
2353                    self.enqueue_buffer_ordered_message(
2354                        BufferOrderedMessage::LanguageServerUpdate {
2355                            language_server_id: *language_server_id,
2356                            message: message.clone(),
2357                        },
2358                    )
2359                    .ok();
2360                }
2361            }
2362            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2363                notification_id: "lsp".into(),
2364                message: message.clone(),
2365            }),
2366            LspStoreEvent::SnippetEdit {
2367                buffer_id,
2368                edits,
2369                most_recent_edit,
2370            } => {
2371                if most_recent_edit.replica_id == self.replica_id() {
2372                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2373                }
2374            }
2375        }
2376    }
2377
2378    fn on_ssh_event(
2379        &mut self,
2380        _: Entity<SshRemoteClient>,
2381        event: &remote::SshRemoteEvent,
2382        cx: &mut Context<Self>,
2383    ) {
2384        match event {
2385            remote::SshRemoteEvent::Disconnected => {
2386                // if self.is_via_ssh() {
2387                // self.collaborators.clear();
2388                self.worktree_store.update(cx, |store, cx| {
2389                    store.disconnected_from_host(cx);
2390                });
2391                self.buffer_store.update(cx, |buffer_store, cx| {
2392                    buffer_store.disconnected_from_host(cx)
2393                });
2394                self.lsp_store.update(cx, |lsp_store, _cx| {
2395                    lsp_store.disconnected_from_ssh_remote()
2396                });
2397                cx.emit(Event::DisconnectedFromSshRemote);
2398            }
2399        }
2400    }
2401
2402    fn on_settings_observer_event(
2403        &mut self,
2404        _: Entity<SettingsObserver>,
2405        event: &SettingsObserverEvent,
2406        cx: &mut Context<Self>,
2407    ) {
2408        match event {
2409            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2410                Err(InvalidSettingsError::LocalSettings { message, path }) => {
2411                    let message =
2412                        format!("Failed to set local settings in {:?}:\n{}", path, message);
2413                    cx.emit(Event::Toast {
2414                        notification_id: "local-settings".into(),
2415                        message,
2416                    });
2417                }
2418                Ok(_) => cx.emit(Event::HideToast {
2419                    notification_id: "local-settings".into(),
2420                }),
2421                Err(_) => {}
2422            },
2423        }
2424    }
2425
2426    fn on_worktree_store_event(
2427        &mut self,
2428        _: Entity<WorktreeStore>,
2429        event: &WorktreeStoreEvent,
2430        cx: &mut Context<Self>,
2431    ) {
2432        match event {
2433            WorktreeStoreEvent::WorktreeAdded(worktree) => {
2434                self.on_worktree_added(worktree, cx);
2435                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2436            }
2437            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2438                cx.emit(Event::WorktreeRemoved(*id));
2439            }
2440            WorktreeStoreEvent::WorktreeReleased(_, id) => {
2441                self.on_worktree_released(*id, cx);
2442            }
2443            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2444            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2445            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2446                self.client()
2447                    .telemetry()
2448                    .report_discovered_project_events(*worktree_id, changes);
2449                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2450            }
2451            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(worktree_id) => {
2452                cx.emit(Event::WorktreeUpdatedGitRepositories(*worktree_id))
2453            }
2454            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2455                cx.emit(Event::DeletedEntry(*worktree_id, *id))
2456            }
2457        }
2458    }
2459
2460    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
2461        {
2462            let mut remotely_created_models = self.remotely_created_models.lock();
2463            if remotely_created_models.retain_count > 0 {
2464                remotely_created_models.worktrees.push(worktree.clone())
2465            }
2466        }
2467        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2468        cx.notify();
2469    }
2470
2471    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2472        if let Some(ssh) = &self.ssh_client {
2473            ssh.read(cx)
2474                .proto_client()
2475                .send(proto::RemoveWorktree {
2476                    worktree_id: id_to_remove.to_proto(),
2477                })
2478                .log_err();
2479        }
2480
2481        cx.notify();
2482    }
2483
2484    fn on_buffer_event(
2485        &mut self,
2486        buffer: Entity<Buffer>,
2487        event: &BufferEvent,
2488        cx: &mut Context<Self>,
2489    ) -> Option<()> {
2490        if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2491            self.request_buffer_diff_recalculation(&buffer, cx);
2492        }
2493
2494        let buffer_id = buffer.read(cx).remote_id();
2495        match event {
2496            BufferEvent::ReloadNeeded => {
2497                if !self.is_via_collab() {
2498                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2499                        .detach_and_log_err(cx);
2500                }
2501            }
2502            BufferEvent::Operation {
2503                operation,
2504                is_local: true,
2505            } => {
2506                let operation = language::proto::serialize_operation(operation);
2507
2508                if let Some(ssh) = &self.ssh_client {
2509                    ssh.read(cx)
2510                        .proto_client()
2511                        .send(proto::UpdateBuffer {
2512                            project_id: 0,
2513                            buffer_id: buffer_id.to_proto(),
2514                            operations: vec![operation.clone()],
2515                        })
2516                        .ok();
2517                }
2518
2519                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2520                    buffer_id,
2521                    operation,
2522                })
2523                .ok();
2524            }
2525
2526            _ => {}
2527        }
2528
2529        None
2530    }
2531
2532    fn on_image_event(
2533        &mut self,
2534        image: Entity<ImageItem>,
2535        event: &ImageItemEvent,
2536        cx: &mut Context<Self>,
2537    ) -> Option<()> {
2538        match event {
2539            ImageItemEvent::ReloadNeeded => {
2540                if !self.is_via_collab() {
2541                    self.reload_images([image.clone()].into_iter().collect(), cx)
2542                        .detach_and_log_err(cx);
2543                }
2544            }
2545            _ => {}
2546        }
2547
2548        None
2549    }
2550
2551    fn request_buffer_diff_recalculation(
2552        &mut self,
2553        buffer: &Entity<Buffer>,
2554        cx: &mut Context<Self>,
2555    ) {
2556        self.buffers_needing_diff.insert(buffer.downgrade());
2557        let first_insertion = self.buffers_needing_diff.len() == 1;
2558
2559        let settings = ProjectSettings::get_global(cx);
2560        let delay = if let Some(delay) = settings.git.gutter_debounce {
2561            delay
2562        } else {
2563            if first_insertion {
2564                let this = cx.weak_entity();
2565                cx.defer(move |cx| {
2566                    if let Some(this) = this.upgrade() {
2567                        this.update(cx, |this, cx| {
2568                            this.recalculate_buffer_diffs(cx).detach();
2569                        });
2570                    }
2571                });
2572            }
2573            return;
2574        };
2575
2576        const MIN_DELAY: u64 = 50;
2577        let delay = delay.max(MIN_DELAY);
2578        let duration = Duration::from_millis(delay);
2579
2580        self.git_diff_debouncer
2581            .fire_new(duration, cx, move |this, cx| {
2582                this.recalculate_buffer_diffs(cx)
2583            });
2584    }
2585
2586    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2587        cx.spawn(move |this, mut cx| async move {
2588            loop {
2589                let task = this
2590                    .update(&mut cx, |this, cx| {
2591                        let buffers = this
2592                            .buffers_needing_diff
2593                            .drain()
2594                            .filter_map(|buffer| buffer.upgrade())
2595                            .collect::<Vec<_>>();
2596                        if buffers.is_empty() {
2597                            None
2598                        } else {
2599                            Some(this.buffer_store.update(cx, |buffer_store, cx| {
2600                                buffer_store.recalculate_buffer_diffs(buffers, cx)
2601                            }))
2602                        }
2603                    })
2604                    .ok()
2605                    .flatten();
2606
2607                if let Some(task) = task {
2608                    task.await;
2609                } else {
2610                    break;
2611                }
2612            }
2613        })
2614    }
2615
2616    pub fn set_language_for_buffer(
2617        &mut self,
2618        buffer: &Entity<Buffer>,
2619        new_language: Arc<Language>,
2620        cx: &mut Context<Self>,
2621    ) {
2622        self.lsp_store.update(cx, |lsp_store, cx| {
2623            lsp_store.set_language_for_buffer(buffer, new_language, cx)
2624        })
2625    }
2626
2627    pub fn restart_language_servers_for_buffers(
2628        &mut self,
2629        buffers: Vec<Entity<Buffer>>,
2630        cx: &mut Context<Self>,
2631    ) {
2632        self.lsp_store.update(cx, |lsp_store, cx| {
2633            lsp_store.restart_language_servers_for_buffers(buffers, cx)
2634        })
2635    }
2636
2637    pub fn cancel_language_server_work_for_buffers(
2638        &mut self,
2639        buffers: impl IntoIterator<Item = Entity<Buffer>>,
2640        cx: &mut Context<Self>,
2641    ) {
2642        self.lsp_store.update(cx, |lsp_store, cx| {
2643            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2644        })
2645    }
2646
2647    pub fn cancel_language_server_work(
2648        &mut self,
2649        server_id: LanguageServerId,
2650        token_to_cancel: Option<String>,
2651        cx: &mut Context<Self>,
2652    ) {
2653        self.lsp_store.update(cx, |lsp_store, cx| {
2654            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2655        })
2656    }
2657
2658    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2659        self.buffer_ordered_messages_tx
2660            .unbounded_send(message)
2661            .map_err(|e| anyhow!(e))
2662    }
2663
2664    pub fn available_toolchains(
2665        &self,
2666        worktree_id: WorktreeId,
2667        language_name: LanguageName,
2668        cx: &App,
2669    ) -> Task<Option<ToolchainList>> {
2670        if let Some(toolchain_store) = self.toolchain_store.clone() {
2671            cx.spawn(|cx| async move {
2672                cx.update(|cx| {
2673                    toolchain_store
2674                        .read(cx)
2675                        .list_toolchains(worktree_id, language_name, cx)
2676                })
2677                .ok()?
2678                .await
2679            })
2680        } else {
2681            Task::ready(None)
2682        }
2683    }
2684
2685    pub async fn toolchain_term(
2686        languages: Arc<LanguageRegistry>,
2687        language_name: LanguageName,
2688    ) -> Option<SharedString> {
2689        languages
2690            .language_for_name(language_name.as_ref())
2691            .await
2692            .ok()?
2693            .toolchain_lister()
2694            .map(|lister| lister.term())
2695    }
2696
2697    pub fn activate_toolchain(
2698        &self,
2699        worktree_id: WorktreeId,
2700        toolchain: Toolchain,
2701        cx: &mut App,
2702    ) -> Task<Option<()>> {
2703        let Some(toolchain_store) = self.toolchain_store.clone() else {
2704            return Task::ready(None);
2705        };
2706        toolchain_store.update(cx, |this, cx| {
2707            this.activate_toolchain(worktree_id, toolchain, cx)
2708        })
2709    }
2710    pub fn active_toolchain(
2711        &self,
2712        worktree_id: WorktreeId,
2713        language_name: LanguageName,
2714        cx: &App,
2715    ) -> Task<Option<Toolchain>> {
2716        let Some(toolchain_store) = self.toolchain_store.clone() else {
2717            return Task::ready(None);
2718        };
2719        toolchain_store
2720            .read(cx)
2721            .active_toolchain(worktree_id, language_name, cx)
2722    }
2723    pub fn language_server_statuses<'a>(
2724        &'a self,
2725        cx: &'a App,
2726    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2727        self.lsp_store.read(cx).language_server_statuses()
2728    }
2729
2730    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
2731        self.lsp_store.read(cx).last_formatting_failure()
2732    }
2733
2734    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
2735        self.lsp_store
2736            .update(cx, |store, _| store.reset_last_formatting_failure());
2737    }
2738
2739    pub fn reload_buffers(
2740        &self,
2741        buffers: HashSet<Entity<Buffer>>,
2742        push_to_history: bool,
2743        cx: &mut Context<Self>,
2744    ) -> Task<Result<ProjectTransaction>> {
2745        self.buffer_store.update(cx, |buffer_store, cx| {
2746            buffer_store.reload_buffers(buffers, push_to_history, cx)
2747        })
2748    }
2749
2750    pub fn reload_images(
2751        &self,
2752        images: HashSet<Entity<ImageItem>>,
2753        cx: &mut Context<Self>,
2754    ) -> Task<Result<()>> {
2755        self.image_store
2756            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
2757    }
2758
2759    pub fn format(
2760        &mut self,
2761        buffers: HashSet<Entity<Buffer>>,
2762        target: LspFormatTarget,
2763        push_to_history: bool,
2764        trigger: lsp_store::FormatTrigger,
2765        cx: &mut Context<Project>,
2766    ) -> Task<anyhow::Result<ProjectTransaction>> {
2767        self.lsp_store.update(cx, |lsp_store, cx| {
2768            lsp_store.format(buffers, target, push_to_history, trigger, cx)
2769        })
2770    }
2771
2772    #[inline(never)]
2773    fn definition_impl(
2774        &mut self,
2775        buffer: &Entity<Buffer>,
2776        position: PointUtf16,
2777        cx: &mut Context<Self>,
2778    ) -> Task<Result<Vec<LocationLink>>> {
2779        self.request_lsp(
2780            buffer.clone(),
2781            LanguageServerToQuery::Primary,
2782            GetDefinition { position },
2783            cx,
2784        )
2785    }
2786    pub fn definition<T: ToPointUtf16>(
2787        &mut self,
2788        buffer: &Entity<Buffer>,
2789        position: T,
2790        cx: &mut Context<Self>,
2791    ) -> Task<Result<Vec<LocationLink>>> {
2792        let position = position.to_point_utf16(buffer.read(cx));
2793        self.definition_impl(buffer, position, cx)
2794    }
2795
2796    fn declaration_impl(
2797        &mut self,
2798        buffer: &Entity<Buffer>,
2799        position: PointUtf16,
2800        cx: &mut Context<Self>,
2801    ) -> Task<Result<Vec<LocationLink>>> {
2802        self.request_lsp(
2803            buffer.clone(),
2804            LanguageServerToQuery::Primary,
2805            GetDeclaration { position },
2806            cx,
2807        )
2808    }
2809
2810    pub fn declaration<T: ToPointUtf16>(
2811        &mut self,
2812        buffer: &Entity<Buffer>,
2813        position: T,
2814        cx: &mut Context<Self>,
2815    ) -> Task<Result<Vec<LocationLink>>> {
2816        let position = position.to_point_utf16(buffer.read(cx));
2817        self.declaration_impl(buffer, position, cx)
2818    }
2819
2820    fn type_definition_impl(
2821        &mut self,
2822        buffer: &Entity<Buffer>,
2823        position: PointUtf16,
2824        cx: &mut Context<Self>,
2825    ) -> Task<Result<Vec<LocationLink>>> {
2826        self.request_lsp(
2827            buffer.clone(),
2828            LanguageServerToQuery::Primary,
2829            GetTypeDefinition { position },
2830            cx,
2831        )
2832    }
2833
2834    pub fn type_definition<T: ToPointUtf16>(
2835        &mut self,
2836        buffer: &Entity<Buffer>,
2837        position: T,
2838        cx: &mut Context<Self>,
2839    ) -> Task<Result<Vec<LocationLink>>> {
2840        let position = position.to_point_utf16(buffer.read(cx));
2841        self.type_definition_impl(buffer, position, cx)
2842    }
2843
2844    pub fn implementation<T: ToPointUtf16>(
2845        &mut self,
2846        buffer: &Entity<Buffer>,
2847        position: T,
2848        cx: &mut Context<Self>,
2849    ) -> Task<Result<Vec<LocationLink>>> {
2850        let position = position.to_point_utf16(buffer.read(cx));
2851        self.request_lsp(
2852            buffer.clone(),
2853            LanguageServerToQuery::Primary,
2854            GetImplementation { position },
2855            cx,
2856        )
2857    }
2858
2859    pub fn references<T: ToPointUtf16>(
2860        &mut self,
2861        buffer: &Entity<Buffer>,
2862        position: T,
2863        cx: &mut Context<Self>,
2864    ) -> Task<Result<Vec<Location>>> {
2865        let position = position.to_point_utf16(buffer.read(cx));
2866        self.request_lsp(
2867            buffer.clone(),
2868            LanguageServerToQuery::Primary,
2869            GetReferences { position },
2870            cx,
2871        )
2872    }
2873
2874    fn document_highlights_impl(
2875        &mut self,
2876        buffer: &Entity<Buffer>,
2877        position: PointUtf16,
2878        cx: &mut Context<Self>,
2879    ) -> Task<Result<Vec<DocumentHighlight>>> {
2880        self.request_lsp(
2881            buffer.clone(),
2882            LanguageServerToQuery::Primary,
2883            GetDocumentHighlights { position },
2884            cx,
2885        )
2886    }
2887
2888    pub fn document_highlights<T: ToPointUtf16>(
2889        &mut self,
2890        buffer: &Entity<Buffer>,
2891        position: T,
2892        cx: &mut Context<Self>,
2893    ) -> Task<Result<Vec<DocumentHighlight>>> {
2894        let position = position.to_point_utf16(buffer.read(cx));
2895        self.document_highlights_impl(buffer, position, cx)
2896    }
2897
2898    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
2899        self.lsp_store
2900            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
2901    }
2902
2903    pub fn open_buffer_for_symbol(
2904        &mut self,
2905        symbol: &Symbol,
2906        cx: &mut Context<Self>,
2907    ) -> Task<Result<Entity<Buffer>>> {
2908        self.lsp_store.update(cx, |lsp_store, cx| {
2909            lsp_store.open_buffer_for_symbol(symbol, cx)
2910        })
2911    }
2912
2913    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
2914        let guard = self.retain_remotely_created_models(cx);
2915        let Some(ssh_client) = self.ssh_client.as_ref() else {
2916            return Task::ready(Err(anyhow!("not an ssh project")));
2917        };
2918
2919        let proto_client = ssh_client.read(cx).proto_client();
2920
2921        cx.spawn(|project, mut cx| async move {
2922            let buffer = proto_client
2923                .request(proto::OpenServerSettings {
2924                    project_id: SSH_PROJECT_ID,
2925                })
2926                .await?;
2927
2928            let buffer = project
2929                .update(&mut cx, |project, cx| {
2930                    project.buffer_store.update(cx, |buffer_store, cx| {
2931                        anyhow::Ok(
2932                            buffer_store
2933                                .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
2934                        )
2935                    })
2936                })??
2937                .await;
2938
2939            drop(guard);
2940            buffer
2941        })
2942    }
2943
2944    pub fn open_local_buffer_via_lsp(
2945        &mut self,
2946        abs_path: lsp::Url,
2947        language_server_id: LanguageServerId,
2948        language_server_name: LanguageServerName,
2949        cx: &mut Context<Self>,
2950    ) -> Task<Result<Entity<Buffer>>> {
2951        self.lsp_store.update(cx, |lsp_store, cx| {
2952            lsp_store.open_local_buffer_via_lsp(
2953                abs_path,
2954                language_server_id,
2955                language_server_name,
2956                cx,
2957            )
2958        })
2959    }
2960
2961    pub fn signature_help<T: ToPointUtf16>(
2962        &self,
2963        buffer: &Entity<Buffer>,
2964        position: T,
2965        cx: &mut Context<Self>,
2966    ) -> Task<Vec<SignatureHelp>> {
2967        self.lsp_store.update(cx, |lsp_store, cx| {
2968            lsp_store.signature_help(buffer, position, cx)
2969        })
2970    }
2971
2972    pub fn hover<T: ToPointUtf16>(
2973        &self,
2974        buffer: &Entity<Buffer>,
2975        position: T,
2976        cx: &mut Context<Self>,
2977    ) -> Task<Vec<Hover>> {
2978        let position = position.to_point_utf16(buffer.read(cx));
2979        self.lsp_store
2980            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
2981    }
2982
2983    pub fn linked_edit(
2984        &self,
2985        buffer: &Entity<Buffer>,
2986        position: Anchor,
2987        cx: &mut Context<Self>,
2988    ) -> Task<Result<Vec<Range<Anchor>>>> {
2989        self.lsp_store.update(cx, |lsp_store, cx| {
2990            lsp_store.linked_edit(buffer, position, cx)
2991        })
2992    }
2993
2994    pub fn completions<T: ToOffset + ToPointUtf16>(
2995        &self,
2996        buffer: &Entity<Buffer>,
2997        position: T,
2998        context: CompletionContext,
2999        cx: &mut Context<Self>,
3000    ) -> Task<Result<Vec<Completion>>> {
3001        let position = position.to_point_utf16(buffer.read(cx));
3002        self.lsp_store.update(cx, |lsp_store, cx| {
3003            lsp_store.completions(buffer, position, context, cx)
3004        })
3005    }
3006
3007    pub fn code_actions<T: Clone + ToOffset>(
3008        &mut self,
3009        buffer_handle: &Entity<Buffer>,
3010        range: Range<T>,
3011        kinds: Option<Vec<CodeActionKind>>,
3012        cx: &mut Context<Self>,
3013    ) -> Task<Result<Vec<CodeAction>>> {
3014        let buffer = buffer_handle.read(cx);
3015        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3016        self.lsp_store.update(cx, |lsp_store, cx| {
3017            lsp_store.code_actions(buffer_handle, range, kinds, cx)
3018        })
3019    }
3020
3021    pub fn apply_code_action(
3022        &self,
3023        buffer_handle: Entity<Buffer>,
3024        action: CodeAction,
3025        push_to_history: bool,
3026        cx: &mut Context<Self>,
3027    ) -> Task<Result<ProjectTransaction>> {
3028        self.lsp_store.update(cx, |lsp_store, cx| {
3029            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3030        })
3031    }
3032
3033    fn prepare_rename_impl(
3034        &mut self,
3035        buffer: Entity<Buffer>,
3036        position: PointUtf16,
3037        cx: &mut Context<Self>,
3038    ) -> Task<Result<PrepareRenameResponse>> {
3039        self.request_lsp(
3040            buffer,
3041            LanguageServerToQuery::Primary,
3042            PrepareRename { position },
3043            cx,
3044        )
3045    }
3046    pub fn prepare_rename<T: ToPointUtf16>(
3047        &mut self,
3048        buffer: Entity<Buffer>,
3049        position: T,
3050        cx: &mut Context<Self>,
3051    ) -> Task<Result<PrepareRenameResponse>> {
3052        let position = position.to_point_utf16(buffer.read(cx));
3053        self.prepare_rename_impl(buffer, position, cx)
3054    }
3055
3056    pub fn perform_rename<T: ToPointUtf16>(
3057        &mut self,
3058        buffer: Entity<Buffer>,
3059        position: T,
3060        new_name: String,
3061        cx: &mut Context<Self>,
3062    ) -> Task<Result<ProjectTransaction>> {
3063        let push_to_history = true;
3064        let position = position.to_point_utf16(buffer.read(cx));
3065        self.request_lsp(
3066            buffer,
3067            LanguageServerToQuery::Primary,
3068            PerformRename {
3069                position,
3070                new_name,
3071                push_to_history,
3072            },
3073            cx,
3074        )
3075    }
3076
3077    pub fn on_type_format<T: ToPointUtf16>(
3078        &mut self,
3079        buffer: Entity<Buffer>,
3080        position: T,
3081        trigger: String,
3082        push_to_history: bool,
3083        cx: &mut Context<Self>,
3084    ) -> Task<Result<Option<Transaction>>> {
3085        self.lsp_store.update(cx, |lsp_store, cx| {
3086            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3087        })
3088    }
3089
3090    pub fn inlay_hints<T: ToOffset>(
3091        &mut self,
3092        buffer_handle: Entity<Buffer>,
3093        range: Range<T>,
3094        cx: &mut Context<Self>,
3095    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3096        let buffer = buffer_handle.read(cx);
3097        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3098        self.lsp_store.update(cx, |lsp_store, cx| {
3099            lsp_store.inlay_hints(buffer_handle, range, cx)
3100        })
3101    }
3102
3103    pub fn resolve_inlay_hint(
3104        &self,
3105        hint: InlayHint,
3106        buffer_handle: Entity<Buffer>,
3107        server_id: LanguageServerId,
3108        cx: &mut Context<Self>,
3109    ) -> Task<anyhow::Result<InlayHint>> {
3110        self.lsp_store.update(cx, |lsp_store, cx| {
3111            lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3112        })
3113    }
3114
3115    pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3116        let (result_tx, result_rx) = smol::channel::unbounded();
3117
3118        let matching_buffers_rx = if query.is_opened_only() {
3119            self.sort_search_candidates(&query, cx)
3120        } else {
3121            self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3122        };
3123
3124        cx.spawn(|_, cx| async move {
3125            let mut range_count = 0;
3126            let mut buffer_count = 0;
3127            let mut limit_reached = false;
3128            let query = Arc::new(query);
3129            let mut chunks = matching_buffers_rx.ready_chunks(64);
3130
3131            // Now that we know what paths match the query, we will load at most
3132            // 64 buffers at a time to avoid overwhelming the main thread. For each
3133            // opened buffer, we will spawn a background task that retrieves all the
3134            // ranges in the buffer matched by the query.
3135            let mut chunks = pin!(chunks);
3136            'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3137                let mut chunk_results = Vec::new();
3138                for buffer in matching_buffer_chunk {
3139                    let buffer = buffer.clone();
3140                    let query = query.clone();
3141                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
3142                    chunk_results.push(cx.background_executor().spawn(async move {
3143                        let ranges = query
3144                            .search(&snapshot, None)
3145                            .await
3146                            .iter()
3147                            .map(|range| {
3148                                snapshot.anchor_before(range.start)
3149                                    ..snapshot.anchor_after(range.end)
3150                            })
3151                            .collect::<Vec<_>>();
3152                        anyhow::Ok((buffer, ranges))
3153                    }));
3154                }
3155
3156                let chunk_results = futures::future::join_all(chunk_results).await;
3157                for result in chunk_results {
3158                    if let Some((buffer, ranges)) = result.log_err() {
3159                        range_count += ranges.len();
3160                        buffer_count += 1;
3161                        result_tx
3162                            .send(SearchResult::Buffer { buffer, ranges })
3163                            .await?;
3164                        if buffer_count > MAX_SEARCH_RESULT_FILES
3165                            || range_count > MAX_SEARCH_RESULT_RANGES
3166                        {
3167                            limit_reached = true;
3168                            break 'outer;
3169                        }
3170                    }
3171                }
3172            }
3173
3174            if limit_reached {
3175                result_tx.send(SearchResult::LimitReached).await?;
3176            }
3177
3178            anyhow::Ok(())
3179        })
3180        .detach();
3181
3182        result_rx
3183    }
3184
3185    fn find_search_candidate_buffers(
3186        &mut self,
3187        query: &SearchQuery,
3188        limit: usize,
3189        cx: &mut Context<Project>,
3190    ) -> Receiver<Entity<Buffer>> {
3191        if self.is_local() {
3192            let fs = self.fs.clone();
3193            self.buffer_store.update(cx, |buffer_store, cx| {
3194                buffer_store.find_search_candidates(query, limit, fs, cx)
3195            })
3196        } else {
3197            self.find_search_candidates_remote(query, limit, cx)
3198        }
3199    }
3200
3201    fn sort_search_candidates(
3202        &mut self,
3203        search_query: &SearchQuery,
3204        cx: &mut Context<Project>,
3205    ) -> Receiver<Entity<Buffer>> {
3206        let worktree_store = self.worktree_store.read(cx);
3207        let mut buffers = search_query
3208            .buffers()
3209            .into_iter()
3210            .flatten()
3211            .filter(|buffer| {
3212                let b = buffer.read(cx);
3213                if let Some(file) = b.file() {
3214                    if !search_query.file_matches(file.path()) {
3215                        return false;
3216                    }
3217                    if let Some(entry) = b
3218                        .entry_id(cx)
3219                        .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3220                    {
3221                        if entry.is_ignored && !search_query.include_ignored() {
3222                            return false;
3223                        }
3224                    }
3225                }
3226                true
3227            })
3228            .collect::<Vec<_>>();
3229        let (tx, rx) = smol::channel::unbounded();
3230        buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3231            (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3232            (None, Some(_)) => std::cmp::Ordering::Less,
3233            (Some(_), None) => std::cmp::Ordering::Greater,
3234            (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3235        });
3236        for buffer in buffers {
3237            tx.send_blocking(buffer.clone()).unwrap()
3238        }
3239
3240        rx
3241    }
3242
3243    fn find_search_candidates_remote(
3244        &mut self,
3245        query: &SearchQuery,
3246        limit: usize,
3247        cx: &mut Context<Project>,
3248    ) -> Receiver<Entity<Buffer>> {
3249        let (tx, rx) = smol::channel::unbounded();
3250
3251        let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3252            (ssh_client.read(cx).proto_client(), 0)
3253        } else if let Some(remote_id) = self.remote_id() {
3254            (self.client.clone().into(), remote_id)
3255        } else {
3256            return rx;
3257        };
3258
3259        let request = client.request(proto::FindSearchCandidates {
3260            project_id: remote_id,
3261            query: Some(query.to_proto()),
3262            limit: limit as _,
3263        });
3264        let guard = self.retain_remotely_created_models(cx);
3265
3266        cx.spawn(move |project, mut cx| async move {
3267            let response = request.await?;
3268            for buffer_id in response.buffer_ids {
3269                let buffer_id = BufferId::new(buffer_id)?;
3270                let buffer = project
3271                    .update(&mut cx, |project, cx| {
3272                        project.buffer_store.update(cx, |buffer_store, cx| {
3273                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
3274                        })
3275                    })?
3276                    .await?;
3277                let _ = tx.send(buffer).await;
3278            }
3279
3280            drop(guard);
3281            anyhow::Ok(())
3282        })
3283        .detach_and_log_err(cx);
3284        rx
3285    }
3286
3287    pub fn request_lsp<R: LspCommand>(
3288        &mut self,
3289        buffer_handle: Entity<Buffer>,
3290        server: LanguageServerToQuery,
3291        request: R,
3292        cx: &mut Context<Self>,
3293    ) -> Task<Result<R::Response>>
3294    where
3295        <R::LspRequest as lsp::request::Request>::Result: Send,
3296        <R::LspRequest as lsp::request::Request>::Params: Send,
3297    {
3298        let guard = self.retain_remotely_created_models(cx);
3299        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3300            lsp_store.request_lsp(buffer_handle, server, request, cx)
3301        });
3302        cx.spawn(|_, _| async move {
3303            let result = task.await;
3304            drop(guard);
3305            result
3306        })
3307    }
3308
3309    /// Move a worktree to a new position in the worktree order.
3310    ///
3311    /// The worktree will moved to the opposite side of the destination worktree.
3312    ///
3313    /// # Example
3314    ///
3315    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3316    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3317    ///
3318    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3319    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3320    ///
3321    /// # Errors
3322    ///
3323    /// An error will be returned if the worktree or destination worktree are not found.
3324    pub fn move_worktree(
3325        &mut self,
3326        source: WorktreeId,
3327        destination: WorktreeId,
3328        cx: &mut Context<'_, Self>,
3329    ) -> Result<()> {
3330        self.worktree_store.update(cx, |worktree_store, cx| {
3331            worktree_store.move_worktree(source, destination, cx)
3332        })
3333    }
3334
3335    pub fn find_or_create_worktree(
3336        &mut self,
3337        abs_path: impl AsRef<Path>,
3338        visible: bool,
3339        cx: &mut Context<Self>,
3340    ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3341        self.worktree_store.update(cx, |worktree_store, cx| {
3342            worktree_store.find_or_create_worktree(abs_path, visible, cx)
3343        })
3344    }
3345
3346    pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3347        self.worktree_store.read_with(cx, |worktree_store, cx| {
3348            worktree_store.find_worktree(abs_path, cx)
3349        })
3350    }
3351
3352    pub fn is_shared(&self) -> bool {
3353        match &self.client_state {
3354            ProjectClientState::Shared { .. } => true,
3355            ProjectClientState::Local => false,
3356            ProjectClientState::Remote { .. } => true,
3357        }
3358    }
3359
3360    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3361    pub fn resolve_path_in_buffer(
3362        &self,
3363        path: &str,
3364        buffer: &Entity<Buffer>,
3365        cx: &mut Context<Self>,
3366    ) -> Task<Option<ResolvedPath>> {
3367        let path_buf = PathBuf::from(path);
3368        if path_buf.is_absolute() || path.starts_with("~") {
3369            self.resolve_abs_path(path, cx)
3370        } else {
3371            self.resolve_path_in_worktrees(path_buf, buffer, cx)
3372        }
3373    }
3374
3375    pub fn resolve_abs_file_path(
3376        &self,
3377        path: &str,
3378        cx: &mut Context<Self>,
3379    ) -> Task<Option<ResolvedPath>> {
3380        let resolve_task = self.resolve_abs_path(path, cx);
3381        cx.background_executor().spawn(async move {
3382            let resolved_path = resolve_task.await;
3383            resolved_path.filter(|path| path.is_file())
3384        })
3385    }
3386
3387    pub fn resolve_abs_path(
3388        &self,
3389        path: &str,
3390        cx: &mut Context<Self>,
3391    ) -> Task<Option<ResolvedPath>> {
3392        if self.is_local() {
3393            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3394            let fs = self.fs.clone();
3395            cx.background_executor().spawn(async move {
3396                let path = expanded.as_path();
3397                let metadata = fs.metadata(path).await.ok().flatten();
3398
3399                metadata.map(|metadata| ResolvedPath::AbsPath {
3400                    path: expanded,
3401                    is_dir: metadata.is_dir,
3402                })
3403            })
3404        } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3405            let request_path = Path::new(path);
3406            let request = ssh_client
3407                .read(cx)
3408                .proto_client()
3409                .request(proto::GetPathMetadata {
3410                    project_id: SSH_PROJECT_ID,
3411                    path: request_path.to_proto(),
3412                });
3413            cx.background_executor().spawn(async move {
3414                let response = request.await.log_err()?;
3415                if response.exists {
3416                    Some(ResolvedPath::AbsPath {
3417                        path: PathBuf::from_proto(response.path),
3418                        is_dir: response.is_dir,
3419                    })
3420                } else {
3421                    None
3422                }
3423            })
3424        } else {
3425            return Task::ready(None);
3426        }
3427    }
3428
3429    fn resolve_path_in_worktrees(
3430        &self,
3431        path: PathBuf,
3432        buffer: &Entity<Buffer>,
3433        cx: &mut Context<Self>,
3434    ) -> Task<Option<ResolvedPath>> {
3435        let mut candidates = vec![path.clone()];
3436
3437        if let Some(file) = buffer.read(cx).file() {
3438            if let Some(dir) = file.path().parent() {
3439                let joined = dir.to_path_buf().join(path);
3440                candidates.push(joined);
3441            }
3442        }
3443
3444        let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3445        cx.spawn(|_, mut cx| async move {
3446            for worktree in worktrees {
3447                for candidate in candidates.iter() {
3448                    let path = worktree
3449                        .update(&mut cx, |worktree, _| {
3450                            let root_entry_path = &worktree.root_entry()?.path;
3451
3452                            let resolved = resolve_path(root_entry_path, candidate);
3453
3454                            let stripped =
3455                                resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3456
3457                            worktree.entry_for_path(stripped).map(|entry| {
3458                                let project_path = ProjectPath {
3459                                    worktree_id: worktree.id(),
3460                                    path: entry.path.clone(),
3461                                };
3462                                ResolvedPath::ProjectPath {
3463                                    project_path,
3464                                    is_dir: entry.is_dir(),
3465                                }
3466                            })
3467                        })
3468                        .ok()?;
3469
3470                    if path.is_some() {
3471                        return path;
3472                    }
3473                }
3474            }
3475            None
3476        })
3477    }
3478
3479    pub fn list_directory(
3480        &self,
3481        query: String,
3482        cx: &mut Context<Self>,
3483    ) -> Task<Result<Vec<PathBuf>>> {
3484        if self.is_local() {
3485            DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3486        } else if let Some(session) = self.ssh_client.as_ref() {
3487            let path_buf = PathBuf::from(query);
3488            let request = proto::ListRemoteDirectory {
3489                dev_server_id: SSH_PROJECT_ID,
3490                path: path_buf.to_proto(),
3491            };
3492
3493            let response = session.read(cx).proto_client().request(request);
3494            cx.background_executor().spawn(async move {
3495                let response = response.await?;
3496                Ok(response.entries.into_iter().map(PathBuf::from).collect())
3497            })
3498        } else {
3499            Task::ready(Err(anyhow!("cannot list directory in remote project")))
3500        }
3501    }
3502
3503    pub fn create_worktree(
3504        &mut self,
3505        abs_path: impl AsRef<Path>,
3506        visible: bool,
3507        cx: &mut Context<Self>,
3508    ) -> Task<Result<Entity<Worktree>>> {
3509        self.worktree_store.update(cx, |worktree_store, cx| {
3510            worktree_store.create_worktree(abs_path, visible, cx)
3511        })
3512    }
3513
3514    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3515        self.worktree_store.update(cx, |worktree_store, cx| {
3516            worktree_store.remove_worktree(id_to_remove, cx);
3517        });
3518    }
3519
3520    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
3521        self.worktree_store.update(cx, |worktree_store, cx| {
3522            worktree_store.add(worktree, cx);
3523        });
3524    }
3525
3526    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
3527        let new_active_entry = entry.and_then(|project_path| {
3528            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3529            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3530            Some(entry.id)
3531        });
3532        if new_active_entry != self.active_entry {
3533            self.active_entry = new_active_entry;
3534            self.lsp_store.update(cx, |lsp_store, _| {
3535                lsp_store.set_active_entry(new_active_entry);
3536            });
3537            cx.emit(Event::ActiveEntryChanged(new_active_entry));
3538        }
3539    }
3540
3541    pub fn language_servers_running_disk_based_diagnostics<'a>(
3542        &'a self,
3543        cx: &'a App,
3544    ) -> impl Iterator<Item = LanguageServerId> + 'a {
3545        self.lsp_store
3546            .read(cx)
3547            .language_servers_running_disk_based_diagnostics()
3548    }
3549
3550    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
3551        self.lsp_store
3552            .read(cx)
3553            .diagnostic_summary(include_ignored, cx)
3554    }
3555
3556    pub fn diagnostic_summaries<'a>(
3557        &'a self,
3558        include_ignored: bool,
3559        cx: &'a App,
3560    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3561        self.lsp_store
3562            .read(cx)
3563            .diagnostic_summaries(include_ignored, cx)
3564    }
3565
3566    pub fn active_entry(&self) -> Option<ProjectEntryId> {
3567        self.active_entry
3568    }
3569
3570    pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
3571        self.worktree_store.read(cx).entry_for_path(path, cx)
3572    }
3573
3574    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
3575        let worktree = self.worktree_for_entry(entry_id, cx)?;
3576        let worktree = worktree.read(cx);
3577        let worktree_id = worktree.id();
3578        let path = worktree.entry_for_id(entry_id)?.path.clone();
3579        Some(ProjectPath { worktree_id, path })
3580    }
3581
3582    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
3583        self.worktree_for_id(project_path.worktree_id, cx)?
3584            .read(cx)
3585            .absolutize(&project_path.path)
3586            .ok()
3587    }
3588
3589    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3590    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3591    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3592    /// the first visible worktree that has an entry for that relative path.
3593    ///
3594    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3595    /// root name from paths.
3596    ///
3597    /// # Arguments
3598    ///
3599    /// * `path` - A full path that starts with a worktree root name, or alternatively a
3600    ///            relative path within a visible worktree.
3601    /// * `cx` - A reference to the `AppContext`.
3602    ///
3603    /// # Returns
3604    ///
3605    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
3606    pub fn find_project_path(&self, path: &Path, cx: &App) -> Option<ProjectPath> {
3607        let worktree_store = self.worktree_store.read(cx);
3608
3609        for worktree in worktree_store.visible_worktrees(cx) {
3610            let worktree_root_name = worktree.read(cx).root_name();
3611            if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
3612                return Some(ProjectPath {
3613                    worktree_id: worktree.read(cx).id(),
3614                    path: relative_path.into(),
3615                });
3616            }
3617        }
3618
3619        for worktree in worktree_store.visible_worktrees(cx) {
3620            let worktree = worktree.read(cx);
3621            if let Some(entry) = worktree.entry_for_path(path) {
3622                return Some(ProjectPath {
3623                    worktree_id: worktree.id(),
3624                    path: entry.path.clone(),
3625                });
3626            }
3627        }
3628
3629        None
3630    }
3631
3632    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
3633        Some(
3634            self.worktree_for_id(project_path.worktree_id, cx)?
3635                .read(cx)
3636                .abs_path()
3637                .to_path_buf(),
3638        )
3639    }
3640
3641    pub fn get_first_worktree_root_repo(&self, cx: &App) -> Option<Arc<dyn GitRepository>> {
3642        let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
3643        let root_entry = worktree.root_git_entry()?;
3644        worktree.get_local_repo(&root_entry)?.repo().clone().into()
3645    }
3646
3647    pub fn branches(&self, project_path: ProjectPath, cx: &App) -> Task<Result<Vec<Branch>>> {
3648        self.worktree_store().read(cx).branches(project_path, cx)
3649    }
3650
3651    pub fn update_or_create_branch(
3652        &self,
3653        repository: ProjectPath,
3654        new_branch: String,
3655        cx: &App,
3656    ) -> Task<Result<()>> {
3657        self.worktree_store()
3658            .read(cx)
3659            .update_or_create_branch(repository, new_branch, cx)
3660    }
3661
3662    pub fn blame_buffer(
3663        &self,
3664        buffer: &Entity<Buffer>,
3665        version: Option<clock::Global>,
3666        cx: &App,
3667    ) -> Task<Result<Option<Blame>>> {
3668        self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
3669    }
3670
3671    pub fn get_permalink_to_line(
3672        &self,
3673        buffer: &Entity<Buffer>,
3674        selection: Range<u32>,
3675        cx: &App,
3676    ) -> Task<Result<url::Url>> {
3677        self.buffer_store
3678            .read(cx)
3679            .get_permalink_to_line(buffer, selection, cx)
3680    }
3681
3682    // RPC message handlers
3683
3684    async fn handle_unshare_project(
3685        this: Entity<Self>,
3686        _: TypedEnvelope<proto::UnshareProject>,
3687        mut cx: AsyncApp,
3688    ) -> Result<()> {
3689        this.update(&mut cx, |this, cx| {
3690            if this.is_local() || this.is_via_ssh() {
3691                this.unshare(cx)?;
3692            } else {
3693                this.disconnected_from_host(cx);
3694            }
3695            Ok(())
3696        })?
3697    }
3698
3699    async fn handle_add_collaborator(
3700        this: Entity<Self>,
3701        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3702        mut cx: AsyncApp,
3703    ) -> Result<()> {
3704        let collaborator = envelope
3705            .payload
3706            .collaborator
3707            .take()
3708            .ok_or_else(|| anyhow!("empty collaborator"))?;
3709
3710        let collaborator = Collaborator::from_proto(collaborator)?;
3711        this.update(&mut cx, |this, cx| {
3712            this.buffer_store.update(cx, |buffer_store, _| {
3713                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
3714            });
3715            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
3716            this.collaborators
3717                .insert(collaborator.peer_id, collaborator);
3718            cx.notify();
3719        })?;
3720
3721        Ok(())
3722    }
3723
3724    async fn handle_update_project_collaborator(
3725        this: Entity<Self>,
3726        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
3727        mut cx: AsyncApp,
3728    ) -> Result<()> {
3729        let old_peer_id = envelope
3730            .payload
3731            .old_peer_id
3732            .ok_or_else(|| anyhow!("missing old peer id"))?;
3733        let new_peer_id = envelope
3734            .payload
3735            .new_peer_id
3736            .ok_or_else(|| anyhow!("missing new peer id"))?;
3737        this.update(&mut cx, |this, cx| {
3738            let collaborator = this
3739                .collaborators
3740                .remove(&old_peer_id)
3741                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
3742            let is_host = collaborator.is_host;
3743            this.collaborators.insert(new_peer_id, collaborator);
3744
3745            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
3746            this.buffer_store.update(cx, |buffer_store, _| {
3747                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
3748            });
3749
3750            if is_host {
3751                this.buffer_store
3752                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
3753                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
3754                    .unwrap();
3755                cx.emit(Event::HostReshared);
3756            }
3757
3758            cx.emit(Event::CollaboratorUpdated {
3759                old_peer_id,
3760                new_peer_id,
3761            });
3762            cx.notify();
3763            Ok(())
3764        })?
3765    }
3766
3767    async fn handle_remove_collaborator(
3768        this: Entity<Self>,
3769        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3770        mut cx: AsyncApp,
3771    ) -> Result<()> {
3772        this.update(&mut cx, |this, cx| {
3773            let peer_id = envelope
3774                .payload
3775                .peer_id
3776                .ok_or_else(|| anyhow!("invalid peer id"))?;
3777            let replica_id = this
3778                .collaborators
3779                .remove(&peer_id)
3780                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3781                .replica_id;
3782            this.buffer_store.update(cx, |buffer_store, cx| {
3783                buffer_store.forget_shared_buffers_for(&peer_id);
3784                for buffer in buffer_store.buffers() {
3785                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3786                }
3787            });
3788
3789            cx.emit(Event::CollaboratorLeft(peer_id));
3790            cx.notify();
3791            Ok(())
3792        })?
3793    }
3794
3795    async fn handle_update_project(
3796        this: Entity<Self>,
3797        envelope: TypedEnvelope<proto::UpdateProject>,
3798        mut cx: AsyncApp,
3799    ) -> Result<()> {
3800        this.update(&mut cx, |this, cx| {
3801            // Don't handle messages that were sent before the response to us joining the project
3802            if envelope.message_id > this.join_project_response_message_id {
3803                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
3804            }
3805            Ok(())
3806        })?
3807    }
3808
3809    async fn handle_toast(
3810        this: Entity<Self>,
3811        envelope: TypedEnvelope<proto::Toast>,
3812        mut cx: AsyncApp,
3813    ) -> Result<()> {
3814        this.update(&mut cx, |_, cx| {
3815            cx.emit(Event::Toast {
3816                notification_id: envelope.payload.notification_id.into(),
3817                message: envelope.payload.message,
3818            });
3819            Ok(())
3820        })?
3821    }
3822
3823    async fn handle_language_server_prompt_request(
3824        this: Entity<Self>,
3825        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
3826        mut cx: AsyncApp,
3827    ) -> Result<proto::LanguageServerPromptResponse> {
3828        let (tx, mut rx) = smol::channel::bounded(1);
3829        let actions: Vec<_> = envelope
3830            .payload
3831            .actions
3832            .into_iter()
3833            .map(|action| MessageActionItem {
3834                title: action,
3835                properties: Default::default(),
3836            })
3837            .collect();
3838        this.update(&mut cx, |_, cx| {
3839            cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
3840                level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
3841                message: envelope.payload.message,
3842                actions: actions.clone(),
3843                lsp_name: envelope.payload.lsp_name,
3844                response_channel: tx,
3845            }));
3846
3847            anyhow::Ok(())
3848        })??;
3849
3850        // We drop `this` to avoid holding a reference in this future for too
3851        // long.
3852        // If we keep the reference, we might not drop the `Project` early
3853        // enough when closing a window and it will only get releases on the
3854        // next `flush_effects()` call.
3855        drop(this);
3856
3857        let mut rx = pin!(rx);
3858        let answer = rx.next().await;
3859
3860        Ok(LanguageServerPromptResponse {
3861            action_response: answer.and_then(|answer| {
3862                actions
3863                    .iter()
3864                    .position(|action| *action == answer)
3865                    .map(|index| index as u64)
3866            }),
3867        })
3868    }
3869
3870    async fn handle_hide_toast(
3871        this: Entity<Self>,
3872        envelope: TypedEnvelope<proto::HideToast>,
3873        mut cx: AsyncApp,
3874    ) -> Result<()> {
3875        this.update(&mut cx, |_, cx| {
3876            cx.emit(Event::HideToast {
3877                notification_id: envelope.payload.notification_id.into(),
3878            });
3879            Ok(())
3880        })?
3881    }
3882
3883    // Collab sends UpdateWorktree protos as messages
3884    async fn handle_update_worktree(
3885        this: Entity<Self>,
3886        envelope: TypedEnvelope<proto::UpdateWorktree>,
3887        mut cx: AsyncApp,
3888    ) -> Result<()> {
3889        this.update(&mut cx, |this, cx| {
3890            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3891            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3892                worktree.update(cx, |worktree, _| {
3893                    let worktree = worktree.as_remote_mut().unwrap();
3894                    worktree.update_from_remote(envelope.payload);
3895                });
3896            }
3897            Ok(())
3898        })?
3899    }
3900
3901    async fn handle_update_buffer_from_ssh(
3902        this: Entity<Self>,
3903        envelope: TypedEnvelope<proto::UpdateBuffer>,
3904        cx: AsyncApp,
3905    ) -> Result<proto::Ack> {
3906        let buffer_store = this.read_with(&cx, |this, cx| {
3907            if let Some(remote_id) = this.remote_id() {
3908                let mut payload = envelope.payload.clone();
3909                payload.project_id = remote_id;
3910                cx.background_executor()
3911                    .spawn(this.client.request(payload))
3912                    .detach_and_log_err(cx);
3913            }
3914            this.buffer_store.clone()
3915        })?;
3916        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3917    }
3918
3919    async fn handle_update_buffer(
3920        this: Entity<Self>,
3921        envelope: TypedEnvelope<proto::UpdateBuffer>,
3922        cx: AsyncApp,
3923    ) -> Result<proto::Ack> {
3924        let buffer_store = this.read_with(&cx, |this, cx| {
3925            if let Some(ssh) = &this.ssh_client {
3926                let mut payload = envelope.payload.clone();
3927                payload.project_id = SSH_PROJECT_ID;
3928                cx.background_executor()
3929                    .spawn(ssh.read(cx).proto_client().request(payload))
3930                    .detach_and_log_err(cx);
3931            }
3932            this.buffer_store.clone()
3933        })?;
3934        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3935    }
3936
3937    fn retain_remotely_created_models(
3938        &mut self,
3939        cx: &mut Context<Self>,
3940    ) -> RemotelyCreatedModelGuard {
3941        {
3942            let mut remotely_create_models = self.remotely_created_models.lock();
3943            if remotely_create_models.retain_count == 0 {
3944                remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
3945                remotely_create_models.worktrees =
3946                    self.worktree_store.read(cx).worktrees().collect();
3947            }
3948            remotely_create_models.retain_count += 1;
3949        }
3950        RemotelyCreatedModelGuard {
3951            remote_models: Arc::downgrade(&self.remotely_created_models),
3952        }
3953    }
3954
3955    async fn handle_create_buffer_for_peer(
3956        this: Entity<Self>,
3957        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
3958        mut cx: AsyncApp,
3959    ) -> Result<()> {
3960        this.update(&mut cx, |this, cx| {
3961            this.buffer_store.update(cx, |buffer_store, cx| {
3962                buffer_store.handle_create_buffer_for_peer(
3963                    envelope,
3964                    this.replica_id(),
3965                    this.capability(),
3966                    cx,
3967                )
3968            })
3969        })?
3970    }
3971
3972    async fn handle_synchronize_buffers(
3973        this: Entity<Self>,
3974        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
3975        mut cx: AsyncApp,
3976    ) -> Result<proto::SynchronizeBuffersResponse> {
3977        let response = this.update(&mut cx, |this, cx| {
3978            let client = this.client.clone();
3979            this.buffer_store.update(cx, |this, cx| {
3980                this.handle_synchronize_buffers(envelope, cx, client)
3981            })
3982        })??;
3983
3984        Ok(response)
3985    }
3986
3987    async fn handle_search_candidate_buffers(
3988        this: Entity<Self>,
3989        envelope: TypedEnvelope<proto::FindSearchCandidates>,
3990        mut cx: AsyncApp,
3991    ) -> Result<proto::FindSearchCandidatesResponse> {
3992        let peer_id = envelope.original_sender_id()?;
3993        let message = envelope.payload;
3994        let query = SearchQuery::from_proto(
3995            message
3996                .query
3997                .ok_or_else(|| anyhow!("missing query field"))?,
3998        )?;
3999        let results = this.update(&mut cx, |this, cx| {
4000            this.find_search_candidate_buffers(&query, message.limit as _, cx)
4001        })?;
4002
4003        let mut response = proto::FindSearchCandidatesResponse {
4004            buffer_ids: Vec::new(),
4005        };
4006
4007        while let Ok(buffer) = results.recv().await {
4008            this.update(&mut cx, |this, cx| {
4009                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4010                response.buffer_ids.push(buffer_id.to_proto());
4011            })?;
4012        }
4013
4014        Ok(response)
4015    }
4016
4017    async fn handle_open_buffer_by_id(
4018        this: Entity<Self>,
4019        envelope: TypedEnvelope<proto::OpenBufferById>,
4020        mut cx: AsyncApp,
4021    ) -> Result<proto::OpenBufferResponse> {
4022        let peer_id = envelope.original_sender_id()?;
4023        let buffer_id = BufferId::new(envelope.payload.id)?;
4024        let buffer = this
4025            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4026            .await?;
4027        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4028    }
4029
4030    async fn handle_open_buffer_by_path(
4031        this: Entity<Self>,
4032        envelope: TypedEnvelope<proto::OpenBufferByPath>,
4033        mut cx: AsyncApp,
4034    ) -> Result<proto::OpenBufferResponse> {
4035        let peer_id = envelope.original_sender_id()?;
4036        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4037        let open_buffer = this.update(&mut cx, |this, cx| {
4038            this.open_buffer(
4039                ProjectPath {
4040                    worktree_id,
4041                    path: Arc::<Path>::from_proto(envelope.payload.path),
4042                },
4043                cx,
4044            )
4045        })?;
4046
4047        let buffer = open_buffer.await?;
4048        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4049    }
4050
4051    async fn handle_open_new_buffer(
4052        this: Entity<Self>,
4053        envelope: TypedEnvelope<proto::OpenNewBuffer>,
4054        mut cx: AsyncApp,
4055    ) -> Result<proto::OpenBufferResponse> {
4056        let buffer = this
4057            .update(&mut cx, |this, cx| this.create_buffer(cx))?
4058            .await?;
4059        let peer_id = envelope.original_sender_id()?;
4060
4061        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4062    }
4063
4064    fn respond_to_open_buffer_request(
4065        this: Entity<Self>,
4066        buffer: Entity<Buffer>,
4067        peer_id: proto::PeerId,
4068        cx: &mut AsyncApp,
4069    ) -> Result<proto::OpenBufferResponse> {
4070        this.update(cx, |this, cx| {
4071            let is_private = buffer
4072                .read(cx)
4073                .file()
4074                .map(|f| f.is_private())
4075                .unwrap_or_default();
4076            if is_private {
4077                Err(anyhow!(ErrorCode::UnsharedItem))
4078            } else {
4079                Ok(proto::OpenBufferResponse {
4080                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4081                })
4082            }
4083        })?
4084    }
4085
4086    fn create_buffer_for_peer(
4087        &mut self,
4088        buffer: &Entity<Buffer>,
4089        peer_id: proto::PeerId,
4090        cx: &mut App,
4091    ) -> BufferId {
4092        self.buffer_store
4093            .update(cx, |buffer_store, cx| {
4094                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4095            })
4096            .detach_and_log_err(cx);
4097        buffer.read(cx).remote_id()
4098    }
4099
4100    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4101        let project_id = match self.client_state {
4102            ProjectClientState::Remote {
4103                sharing_has_stopped,
4104                remote_id,
4105                ..
4106            } => {
4107                if sharing_has_stopped {
4108                    return Task::ready(Err(anyhow!(
4109                        "can't synchronize remote buffers on a readonly project"
4110                    )));
4111                } else {
4112                    remote_id
4113                }
4114            }
4115            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4116                return Task::ready(Err(anyhow!(
4117                    "can't synchronize remote buffers on a local project"
4118                )))
4119            }
4120        };
4121
4122        let client = self.client.clone();
4123        cx.spawn(move |this, mut cx| async move {
4124            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
4125                this.buffer_store.read(cx).buffer_version_info(cx)
4126            })?;
4127            let response = client
4128                .request(proto::SynchronizeBuffers {
4129                    project_id,
4130                    buffers,
4131                })
4132                .await?;
4133
4134            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
4135                response
4136                    .buffers
4137                    .into_iter()
4138                    .map(|buffer| {
4139                        let client = client.clone();
4140                        let buffer_id = match BufferId::new(buffer.id) {
4141                            Ok(id) => id,
4142                            Err(e) => {
4143                                return Task::ready(Err(e));
4144                            }
4145                        };
4146                        let remote_version = language::proto::deserialize_version(&buffer.version);
4147                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4148                            let operations =
4149                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
4150                            cx.background_executor().spawn(async move {
4151                                let operations = operations.await;
4152                                for chunk in split_operations(operations) {
4153                                    client
4154                                        .request(proto::UpdateBuffer {
4155                                            project_id,
4156                                            buffer_id: buffer_id.into(),
4157                                            operations: chunk,
4158                                        })
4159                                        .await?;
4160                                }
4161                                anyhow::Ok(())
4162                            })
4163                        } else {
4164                            Task::ready(Ok(()))
4165                        }
4166                    })
4167                    .collect::<Vec<_>>()
4168            })?;
4169
4170            // Any incomplete buffers have open requests waiting. Request that the host sends
4171            // creates these buffers for us again to unblock any waiting futures.
4172            for id in incomplete_buffer_ids {
4173                cx.background_executor()
4174                    .spawn(client.request(proto::OpenBufferById {
4175                        project_id,
4176                        id: id.into(),
4177                    }))
4178                    .detach();
4179            }
4180
4181            futures::future::join_all(send_updates_for_buffers)
4182                .await
4183                .into_iter()
4184                .collect()
4185        })
4186    }
4187
4188    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4189        self.worktree_store.read(cx).worktree_metadata_protos(cx)
4190    }
4191
4192    /// Iterator of all open buffers that have unsaved changes
4193    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4194        self.buffer_store.read(cx).buffers().filter_map(|buf| {
4195            let buf = buf.read(cx);
4196            if buf.is_dirty() {
4197                buf.project_path(cx)
4198            } else {
4199                None
4200            }
4201        })
4202    }
4203
4204    fn set_worktrees_from_proto(
4205        &mut self,
4206        worktrees: Vec<proto::WorktreeMetadata>,
4207        cx: &mut Context<Project>,
4208    ) -> Result<()> {
4209        cx.notify();
4210        self.worktree_store.update(cx, |worktree_store, cx| {
4211            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4212        })
4213    }
4214
4215    fn set_collaborators_from_proto(
4216        &mut self,
4217        messages: Vec<proto::Collaborator>,
4218        cx: &mut Context<Self>,
4219    ) -> Result<()> {
4220        let mut collaborators = HashMap::default();
4221        for message in messages {
4222            let collaborator = Collaborator::from_proto(message)?;
4223            collaborators.insert(collaborator.peer_id, collaborator);
4224        }
4225        for old_peer_id in self.collaborators.keys() {
4226            if !collaborators.contains_key(old_peer_id) {
4227                cx.emit(Event::CollaboratorLeft(*old_peer_id));
4228            }
4229        }
4230        self.collaborators = collaborators;
4231        Ok(())
4232    }
4233
4234    pub fn supplementary_language_servers<'a>(
4235        &'a self,
4236        cx: &'a App,
4237    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4238        self.lsp_store.read(cx).supplementary_language_servers()
4239    }
4240
4241    pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4242        self.lsp_store.update(cx, |this, cx| {
4243            this.language_servers_for_local_buffer(buffer, cx)
4244                .any(
4245                    |(_, server)| match server.capabilities().inlay_hint_provider {
4246                        Some(lsp::OneOf::Left(enabled)) => enabled,
4247                        Some(lsp::OneOf::Right(_)) => true,
4248                        None => false,
4249                    },
4250                )
4251        })
4252    }
4253
4254    pub fn language_server_id_for_name(
4255        &self,
4256        buffer: &Buffer,
4257        name: &str,
4258        cx: &mut App,
4259    ) -> Option<LanguageServerId> {
4260        self.lsp_store.update(cx, |this, cx| {
4261            this.language_servers_for_local_buffer(buffer, cx)
4262                .find_map(|(adapter, server)| {
4263                    if adapter.name.0 == name {
4264                        Some(server.server_id())
4265                    } else {
4266                        None
4267                    }
4268                })
4269        })
4270    }
4271
4272    pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
4273        self.lsp_store.update(cx, |this, cx| {
4274            this.language_servers_for_local_buffer(buffer, cx)
4275                .next()
4276                .is_some()
4277        })
4278    }
4279
4280    pub fn buffer_store(&self) -> &Entity<BufferStore> {
4281        &self.buffer_store
4282    }
4283
4284    pub fn git_store(&self) -> &Entity<GitStore> {
4285        &self.git_store
4286    }
4287
4288    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
4289        self.git_store.read(cx).active_repository()
4290    }
4291
4292    pub fn all_repositories(&self, cx: &App) -> Vec<Entity<Repository>> {
4293        self.git_store.read(cx).all_repositories()
4294    }
4295
4296    pub fn repository_and_path_for_buffer_id(
4297        &self,
4298        buffer_id: BufferId,
4299        cx: &App,
4300    ) -> Option<(Entity<Repository>, RepoPath)> {
4301        let path = self
4302            .buffer_for_id(buffer_id, cx)?
4303            .read(cx)
4304            .project_path(cx)?;
4305        self.git_store
4306            .read(cx)
4307            .all_repositories()
4308            .into_iter()
4309            .find_map(|repo| {
4310                Some((
4311                    repo.clone(),
4312                    repo.read(cx).repository_entry.relativize(&path.path).ok()?,
4313                ))
4314            })
4315    }
4316}
4317
4318fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
4319    code_actions
4320        .iter()
4321        .flat_map(|(kind, enabled)| {
4322            if *enabled {
4323                Some(kind.clone().into())
4324            } else {
4325                None
4326            }
4327        })
4328        .collect()
4329}
4330
4331pub struct PathMatchCandidateSet {
4332    pub snapshot: Snapshot,
4333    pub include_ignored: bool,
4334    pub include_root_name: bool,
4335    pub candidates: Candidates,
4336}
4337
4338pub enum Candidates {
4339    /// Only consider directories.
4340    Directories,
4341    /// Only consider files.
4342    Files,
4343    /// Consider directories and files.
4344    Entries,
4345}
4346
4347impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4348    type Candidates = PathMatchCandidateSetIter<'a>;
4349
4350    fn id(&self) -> usize {
4351        self.snapshot.id().to_usize()
4352    }
4353
4354    fn len(&self) -> usize {
4355        match self.candidates {
4356            Candidates::Files => {
4357                if self.include_ignored {
4358                    self.snapshot.file_count()
4359                } else {
4360                    self.snapshot.visible_file_count()
4361                }
4362            }
4363
4364            Candidates::Directories => {
4365                if self.include_ignored {
4366                    self.snapshot.dir_count()
4367                } else {
4368                    self.snapshot.visible_dir_count()
4369                }
4370            }
4371
4372            Candidates::Entries => {
4373                if self.include_ignored {
4374                    self.snapshot.entry_count()
4375                } else {
4376                    self.snapshot.visible_entry_count()
4377                }
4378            }
4379        }
4380    }
4381
4382    fn prefix(&self) -> Arc<str> {
4383        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4384            self.snapshot.root_name().into()
4385        } else if self.include_root_name {
4386            format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4387        } else {
4388            Arc::default()
4389        }
4390    }
4391
4392    fn candidates(&'a self, start: usize) -> Self::Candidates {
4393        PathMatchCandidateSetIter {
4394            traversal: match self.candidates {
4395                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4396                Candidates::Files => self.snapshot.files(self.include_ignored, start),
4397                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4398            },
4399        }
4400    }
4401}
4402
4403pub struct PathMatchCandidateSetIter<'a> {
4404    traversal: Traversal<'a>,
4405}
4406
4407impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4408    type Item = fuzzy::PathMatchCandidate<'a>;
4409
4410    fn next(&mut self) -> Option<Self::Item> {
4411        self.traversal
4412            .next()
4413            .map(|entry| fuzzy::PathMatchCandidate {
4414                is_dir: entry.kind.is_dir(),
4415                path: &entry.path,
4416                char_bag: entry.char_bag,
4417            })
4418    }
4419}
4420
4421impl EventEmitter<Event> for Project {}
4422
4423impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4424    fn from(val: &'a ProjectPath) -> Self {
4425        SettingsLocation {
4426            worktree_id: val.worktree_id,
4427            path: val.path.as_ref(),
4428        }
4429    }
4430}
4431
4432impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4433    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4434        Self {
4435            worktree_id,
4436            path: path.as_ref().into(),
4437        }
4438    }
4439}
4440
4441pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4442    let mut path_components = path.components();
4443    let mut base_components = base.components();
4444    let mut components: Vec<Component> = Vec::new();
4445    loop {
4446        match (path_components.next(), base_components.next()) {
4447            (None, None) => break,
4448            (Some(a), None) => {
4449                components.push(a);
4450                components.extend(path_components.by_ref());
4451                break;
4452            }
4453            (None, _) => components.push(Component::ParentDir),
4454            (Some(a), Some(b)) if components.is_empty() && a == b => (),
4455            (Some(a), Some(Component::CurDir)) => components.push(a),
4456            (Some(a), Some(_)) => {
4457                components.push(Component::ParentDir);
4458                for _ in base_components {
4459                    components.push(Component::ParentDir);
4460                }
4461                components.push(a);
4462                components.extend(path_components.by_ref());
4463                break;
4464            }
4465        }
4466    }
4467    components.iter().map(|c| c.as_os_str()).collect()
4468}
4469
4470fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4471    let mut result = base.to_path_buf();
4472    for component in path.components() {
4473        match component {
4474            Component::ParentDir => {
4475                result.pop();
4476            }
4477            Component::CurDir => (),
4478            _ => result.push(component),
4479        }
4480    }
4481    result
4482}
4483
4484/// ResolvedPath is a path that has been resolved to either a ProjectPath
4485/// or an AbsPath and that *exists*.
4486#[derive(Debug, Clone)]
4487pub enum ResolvedPath {
4488    ProjectPath {
4489        project_path: ProjectPath,
4490        is_dir: bool,
4491    },
4492    AbsPath {
4493        path: PathBuf,
4494        is_dir: bool,
4495    },
4496}
4497
4498impl ResolvedPath {
4499    pub fn abs_path(&self) -> Option<&Path> {
4500        match self {
4501            Self::AbsPath { path, .. } => Some(path.as_path()),
4502            _ => None,
4503        }
4504    }
4505
4506    pub fn project_path(&self) -> Option<&ProjectPath> {
4507        match self {
4508            Self::ProjectPath { project_path, .. } => Some(&project_path),
4509            _ => None,
4510        }
4511    }
4512
4513    pub fn is_file(&self) -> bool {
4514        !self.is_dir()
4515    }
4516
4517    pub fn is_dir(&self) -> bool {
4518        match self {
4519            Self::ProjectPath { is_dir, .. } => *is_dir,
4520            Self::AbsPath { is_dir, .. } => *is_dir,
4521        }
4522    }
4523}
4524
4525impl ProjectItem for Buffer {
4526    fn try_open(
4527        project: &Entity<Project>,
4528        path: &ProjectPath,
4529        cx: &mut App,
4530    ) -> Option<Task<Result<Entity<Self>>>> {
4531        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4532    }
4533
4534    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
4535        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4536    }
4537
4538    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
4539        File::from_dyn(self.file()).map(|file| ProjectPath {
4540            worktree_id: file.worktree_id(cx),
4541            path: file.path().clone(),
4542        })
4543    }
4544
4545    fn is_dirty(&self) -> bool {
4546        self.is_dirty()
4547    }
4548}
4549
4550impl Completion {
4551    /// A key that can be used to sort completions when displaying
4552    /// them to the user.
4553    pub fn sort_key(&self) -> (usize, &str) {
4554        let kind_key = match self.lsp_completion.kind {
4555            Some(lsp::CompletionItemKind::KEYWORD) => 0,
4556            Some(lsp::CompletionItemKind::VARIABLE) => 1,
4557            _ => 2,
4558        };
4559        (kind_key, &self.label.text[self.label.filter_range.clone()])
4560    }
4561
4562    /// Whether this completion is a snippet.
4563    pub fn is_snippet(&self) -> bool {
4564        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
4565    }
4566
4567    /// Returns the corresponding color for this completion.
4568    ///
4569    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
4570    pub fn color(&self) -> Option<Hsla> {
4571        match self.lsp_completion.kind {
4572            Some(CompletionItemKind::COLOR) => color_extractor::extract_color(&self.lsp_completion),
4573            _ => None,
4574        }
4575    }
4576}
4577
4578pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
4579    entries.sort_by(|entry_a, entry_b| {
4580        let entry_a = entry_a.as_ref();
4581        let entry_b = entry_b.as_ref();
4582        compare_paths(
4583            (&entry_a.path, entry_a.is_file()),
4584            (&entry_b.path, entry_b.is_file()),
4585        )
4586    });
4587}
4588
4589fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
4590    match level {
4591        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
4592        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
4593        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
4594    }
4595}