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, File as _, Language, LanguageName, LanguageRegistry, PointUtf16, ToOffset,
  62    ToPointUtf16, Toolchain, ToolchainList, Transaction, Unclipped,
  63};
  64use lsp::{
  65    CodeActionKind, CompletionContext, CompletionItemKind, DocumentHighlightKind, LanguageServerId,
  66    LanguageServerName, MessageActionItem,
  67};
  68use lsp_command::*;
  69use lsp_store::{CompletionDocumentation, 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, TaskContexts, 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_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_spawn(async move {
1168                if let Some(shutdown) = shutdown {
1169                    shutdown.await;
1170                }
1171            })
1172            .detach()
1173        }
1174
1175        match &self.client_state {
1176            ProjectClientState::Local => {}
1177            ProjectClientState::Shared { .. } => {
1178                let _ = self.unshare_internal(cx);
1179            }
1180            ProjectClientState::Remote { remote_id, .. } => {
1181                let _ = self.client.send(proto::LeaveProject {
1182                    project_id: *remote_id,
1183                });
1184                self.disconnected_from_host_internal(cx);
1185            }
1186        }
1187    }
1188
1189    #[cfg(any(test, feature = "test-support"))]
1190    pub async fn example(
1191        root_paths: impl IntoIterator<Item = &Path>,
1192        cx: &mut AsyncApp,
1193    ) -> Entity<Project> {
1194        use clock::FakeSystemClock;
1195
1196        let fs = Arc::new(RealFs::default());
1197        let languages = LanguageRegistry::test(cx.background_executor().clone());
1198        let clock = Arc::new(FakeSystemClock::new());
1199        let http_client = http_client::FakeHttpClient::with_404_response();
1200        let client = cx
1201            .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1202            .unwrap();
1203        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx)).unwrap();
1204        let project = cx
1205            .update(|cx| {
1206                Project::local(
1207                    client,
1208                    node_runtime::NodeRuntime::unavailable(),
1209                    user_store,
1210                    Arc::new(languages),
1211                    fs,
1212                    None,
1213                    cx,
1214                )
1215            })
1216            .unwrap();
1217        for path in root_paths {
1218            let (tree, _) = project
1219                .update(cx, |project, cx| {
1220                    project.find_or_create_worktree(path, true, cx)
1221                })
1222                .unwrap()
1223                .await
1224                .unwrap();
1225            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1226                .unwrap()
1227                .await;
1228        }
1229        project
1230    }
1231
1232    #[cfg(any(test, feature = "test-support"))]
1233    pub async fn test(
1234        fs: Arc<dyn Fs>,
1235        root_paths: impl IntoIterator<Item = &Path>,
1236        cx: &mut gpui::TestAppContext,
1237    ) -> Entity<Project> {
1238        use clock::FakeSystemClock;
1239
1240        let languages = LanguageRegistry::test(cx.executor());
1241        let clock = Arc::new(FakeSystemClock::new());
1242        let http_client = http_client::FakeHttpClient::with_404_response();
1243        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1244        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1245        let project = cx.update(|cx| {
1246            Project::local(
1247                client,
1248                node_runtime::NodeRuntime::unavailable(),
1249                user_store,
1250                Arc::new(languages),
1251                fs,
1252                None,
1253                cx,
1254            )
1255        });
1256        for path in root_paths {
1257            let (tree, _) = project
1258                .update(cx, |project, cx| {
1259                    project.find_or_create_worktree(path, true, cx)
1260                })
1261                .await
1262                .unwrap();
1263
1264            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1265                .await;
1266        }
1267        project
1268    }
1269
1270    pub fn lsp_store(&self) -> Entity<LspStore> {
1271        self.lsp_store.clone()
1272    }
1273
1274    pub fn worktree_store(&self) -> Entity<WorktreeStore> {
1275        self.worktree_store.clone()
1276    }
1277
1278    pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
1279        self.buffer_store.read(cx).get(remote_id)
1280    }
1281
1282    pub fn languages(&self) -> &Arc<LanguageRegistry> {
1283        &self.languages
1284    }
1285
1286    pub fn client(&self) -> Arc<Client> {
1287        self.client.clone()
1288    }
1289
1290    pub fn ssh_client(&self) -> Option<Entity<SshRemoteClient>> {
1291        self.ssh_client.clone()
1292    }
1293
1294    pub fn user_store(&self) -> Entity<UserStore> {
1295        self.user_store.clone()
1296    }
1297
1298    pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1299        self.node.as_ref()
1300    }
1301
1302    pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
1303        self.buffer_store.read(cx).buffers().collect()
1304    }
1305
1306    pub fn environment(&self) -> &Entity<ProjectEnvironment> {
1307        &self.environment
1308    }
1309
1310    pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
1311        self.environment.read(cx).get_cli_environment()
1312    }
1313
1314    pub fn shell_environment_errors<'a>(
1315        &'a self,
1316        cx: &'a App,
1317    ) -> impl Iterator<Item = (&'a WorktreeId, &'a EnvironmentErrorMessage)> {
1318        self.environment.read(cx).environment_errors()
1319    }
1320
1321    pub fn remove_environment_error(&mut self, cx: &mut Context<Self>, worktree_id: WorktreeId) {
1322        self.environment.update(cx, |environment, _| {
1323            environment.remove_environment_error(worktree_id);
1324        });
1325    }
1326
1327    #[cfg(any(test, feature = "test-support"))]
1328    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
1329        self.buffer_store
1330            .read(cx)
1331            .get_by_path(&path.into(), cx)
1332            .is_some()
1333    }
1334
1335    pub fn fs(&self) -> &Arc<dyn Fs> {
1336        &self.fs
1337    }
1338
1339    pub fn remote_id(&self) -> Option<u64> {
1340        match self.client_state {
1341            ProjectClientState::Local => None,
1342            ProjectClientState::Shared { remote_id, .. }
1343            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1344        }
1345    }
1346
1347    pub fn supports_terminal(&self, _cx: &App) -> bool {
1348        if self.is_local() {
1349            return true;
1350        }
1351        if self.is_via_ssh() {
1352            return true;
1353        }
1354
1355        return false;
1356    }
1357
1358    pub fn ssh_connection_string(&self, cx: &App) -> Option<SharedString> {
1359        if let Some(ssh_state) = &self.ssh_client {
1360            return Some(ssh_state.read(cx).connection_string().into());
1361        }
1362
1363        return None;
1364    }
1365
1366    pub fn ssh_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
1367        self.ssh_client
1368            .as_ref()
1369            .map(|ssh| ssh.read(cx).connection_state())
1370    }
1371
1372    pub fn ssh_connection_options(&self, cx: &App) -> Option<SshConnectionOptions> {
1373        self.ssh_client
1374            .as_ref()
1375            .map(|ssh| ssh.read(cx).connection_options())
1376    }
1377
1378    pub fn replica_id(&self) -> ReplicaId {
1379        match self.client_state {
1380            ProjectClientState::Remote { replica_id, .. } => replica_id,
1381            _ => {
1382                if self.ssh_client.is_some() {
1383                    1
1384                } else {
1385                    0
1386                }
1387            }
1388        }
1389    }
1390
1391    pub fn task_store(&self) -> &Entity<TaskStore> {
1392        &self.task_store
1393    }
1394
1395    pub fn snippets(&self) -> &Entity<SnippetProvider> {
1396        &self.snippets
1397    }
1398
1399    pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1400        match kind {
1401            SearchInputKind::Query => &self.search_history,
1402            SearchInputKind::Include => &self.search_included_history,
1403            SearchInputKind::Exclude => &self.search_excluded_history,
1404        }
1405    }
1406
1407    pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1408        match kind {
1409            SearchInputKind::Query => &mut self.search_history,
1410            SearchInputKind::Include => &mut self.search_included_history,
1411            SearchInputKind::Exclude => &mut self.search_excluded_history,
1412        }
1413    }
1414
1415    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1416        &self.collaborators
1417    }
1418
1419    pub fn host(&self) -> Option<&Collaborator> {
1420        self.collaborators.values().find(|c| c.is_host)
1421    }
1422
1423    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
1424        self.worktree_store.update(cx, |store, _| {
1425            store.set_worktrees_reordered(worktrees_reordered);
1426        });
1427    }
1428
1429    /// Collect all worktrees, including ones that don't appear in the project panel
1430    pub fn worktrees<'a>(
1431        &self,
1432        cx: &'a App,
1433    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1434        self.worktree_store.read(cx).worktrees()
1435    }
1436
1437    /// Collect all user-visible worktrees, the ones that appear in the project panel.
1438    pub fn visible_worktrees<'a>(
1439        &'a self,
1440        cx: &'a App,
1441    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1442        self.worktree_store.read(cx).visible_worktrees(cx)
1443    }
1444
1445    pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
1446        self.visible_worktrees(cx)
1447            .map(|tree| tree.read(cx).root_name())
1448    }
1449
1450    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
1451        self.worktree_store.read(cx).worktree_for_id(id, cx)
1452    }
1453
1454    pub fn worktree_for_entry(
1455        &self,
1456        entry_id: ProjectEntryId,
1457        cx: &App,
1458    ) -> Option<Entity<Worktree>> {
1459        self.worktree_store
1460            .read(cx)
1461            .worktree_for_entry(entry_id, cx)
1462    }
1463
1464    pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
1465        self.worktree_for_entry(entry_id, cx)
1466            .map(|worktree| worktree.read(cx).id())
1467    }
1468
1469    /// Checks if the entry is the root of a worktree.
1470    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
1471        self.worktree_for_entry(entry_id, cx)
1472            .map(|worktree| {
1473                worktree
1474                    .read(cx)
1475                    .root_entry()
1476                    .is_some_and(|e| e.id == entry_id)
1477            })
1478            .unwrap_or(false)
1479    }
1480
1481    pub fn project_path_git_status(
1482        &self,
1483        project_path: &ProjectPath,
1484        cx: &App,
1485    ) -> Option<FileStatus> {
1486        self.worktree_for_id(project_path.worktree_id, cx)
1487            .and_then(|worktree| worktree.read(cx).status_for_file(&project_path.path))
1488    }
1489
1490    pub fn visibility_for_paths(
1491        &self,
1492        paths: &[PathBuf],
1493        metadatas: &[Metadata],
1494        exclude_sub_dirs: bool,
1495        cx: &App,
1496    ) -> Option<bool> {
1497        paths
1498            .iter()
1499            .zip(metadatas)
1500            .map(|(path, metadata)| self.visibility_for_path(path, metadata, exclude_sub_dirs, cx))
1501            .max()
1502            .flatten()
1503    }
1504
1505    pub fn visibility_for_path(
1506        &self,
1507        path: &Path,
1508        metadata: &Metadata,
1509        exclude_sub_dirs: bool,
1510        cx: &App,
1511    ) -> Option<bool> {
1512        let sanitized_path = SanitizedPath::from(path);
1513        let path = sanitized_path.as_path();
1514        self.worktrees(cx)
1515            .filter_map(|worktree| {
1516                let worktree = worktree.read(cx);
1517                let abs_path = worktree.as_local()?.abs_path();
1518                let contains = path == abs_path
1519                    || (path.starts_with(abs_path) && (!exclude_sub_dirs || !metadata.is_dir));
1520                contains.then(|| worktree.is_visible())
1521            })
1522            .max()
1523    }
1524
1525    pub fn create_entry(
1526        &mut self,
1527        project_path: impl Into<ProjectPath>,
1528        is_directory: bool,
1529        cx: &mut Context<Self>,
1530    ) -> Task<Result<CreatedEntry>> {
1531        let project_path = project_path.into();
1532        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1533            return Task::ready(Err(anyhow!(format!(
1534                "No worktree for path {project_path:?}"
1535            ))));
1536        };
1537        worktree.update(cx, |worktree, cx| {
1538            worktree.create_entry(project_path.path, is_directory, cx)
1539        })
1540    }
1541
1542    pub fn copy_entry(
1543        &mut self,
1544        entry_id: ProjectEntryId,
1545        relative_worktree_source_path: Option<PathBuf>,
1546        new_path: impl Into<Arc<Path>>,
1547        cx: &mut Context<Self>,
1548    ) -> Task<Result<Option<Entry>>> {
1549        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1550            return Task::ready(Ok(None));
1551        };
1552        worktree.update(cx, |worktree, cx| {
1553            worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1554        })
1555    }
1556
1557    /// Renames the project entry with given `entry_id`.
1558    ///
1559    /// `new_path` is a relative path to worktree root.
1560    /// If root entry is renamed then its new root name is used instead.
1561    pub fn rename_entry(
1562        &mut self,
1563        entry_id: ProjectEntryId,
1564        new_path: impl Into<Arc<Path>>,
1565        cx: &mut Context<Self>,
1566    ) -> Task<Result<CreatedEntry>> {
1567        let worktree_store = self.worktree_store.read(cx);
1568        let new_path = new_path.into();
1569        let Some((worktree, old_path, is_dir)) = worktree_store
1570            .worktree_and_entry_for_id(entry_id, cx)
1571            .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
1572        else {
1573            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1574        };
1575
1576        let worktree_id = worktree.read(cx).id();
1577        let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
1578
1579        let lsp_store = self.lsp_store().downgrade();
1580        cx.spawn(|_, mut cx| async move {
1581            let (old_abs_path, new_abs_path) = {
1582                let root_path = worktree.update(&mut cx, |this, _| this.abs_path())?;
1583                let new_abs_path = if is_root_entry {
1584                    root_path.parent().unwrap().join(&new_path)
1585                } else {
1586                    root_path.join(&new_path)
1587                };
1588                (root_path.join(&old_path), new_abs_path)
1589            };
1590            LspStore::will_rename_entry(
1591                lsp_store.clone(),
1592                worktree_id,
1593                &old_abs_path,
1594                &new_abs_path,
1595                is_dir,
1596                cx.clone(),
1597            )
1598            .await;
1599
1600            let entry = worktree
1601                .update(&mut cx, |worktree, cx| {
1602                    worktree.rename_entry(entry_id, new_path.clone(), cx)
1603                })?
1604                .await?;
1605
1606            lsp_store
1607                .update(&mut cx, |this, _| {
1608                    this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
1609                })
1610                .ok();
1611            Ok(entry)
1612        })
1613    }
1614
1615    pub fn delete_file(
1616        &mut self,
1617        path: ProjectPath,
1618        trash: bool,
1619        cx: &mut Context<Self>,
1620    ) -> Option<Task<Result<()>>> {
1621        let entry = self.entry_for_path(&path, cx)?;
1622        self.delete_entry(entry.id, trash, cx)
1623    }
1624
1625    pub fn delete_entry(
1626        &mut self,
1627        entry_id: ProjectEntryId,
1628        trash: bool,
1629        cx: &mut Context<Self>,
1630    ) -> Option<Task<Result<()>>> {
1631        let worktree = self.worktree_for_entry(entry_id, cx)?;
1632        cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
1633        worktree.update(cx, |worktree, cx| {
1634            worktree.delete_entry(entry_id, trash, cx)
1635        })
1636    }
1637
1638    pub fn expand_entry(
1639        &mut self,
1640        worktree_id: WorktreeId,
1641        entry_id: ProjectEntryId,
1642        cx: &mut Context<Self>,
1643    ) -> Option<Task<Result<()>>> {
1644        let worktree = self.worktree_for_id(worktree_id, cx)?;
1645        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1646    }
1647
1648    pub fn expand_all_for_entry(
1649        &mut self,
1650        worktree_id: WorktreeId,
1651        entry_id: ProjectEntryId,
1652        cx: &mut Context<Self>,
1653    ) -> Option<Task<Result<()>>> {
1654        let worktree = self.worktree_for_id(worktree_id, cx)?;
1655        let task = worktree.update(cx, |worktree, cx| {
1656            worktree.expand_all_for_entry(entry_id, cx)
1657        });
1658        Some(cx.spawn(|this, mut cx| async move {
1659            task.ok_or_else(|| anyhow!("no task"))?.await?;
1660            this.update(&mut cx, |_, cx| {
1661                cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
1662            })?;
1663            Ok(())
1664        }))
1665    }
1666
1667    pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
1668        if !matches!(self.client_state, ProjectClientState::Local) {
1669            return Err(anyhow!("project was already shared"));
1670        }
1671
1672        self.client_subscriptions.extend([
1673            self.client
1674                .subscribe_to_entity(project_id)?
1675                .set_entity(&cx.entity(), &mut cx.to_async()),
1676            self.client
1677                .subscribe_to_entity(project_id)?
1678                .set_entity(&self.worktree_store, &mut cx.to_async()),
1679            self.client
1680                .subscribe_to_entity(project_id)?
1681                .set_entity(&self.buffer_store, &mut cx.to_async()),
1682            self.client
1683                .subscribe_to_entity(project_id)?
1684                .set_entity(&self.lsp_store, &mut cx.to_async()),
1685            self.client
1686                .subscribe_to_entity(project_id)?
1687                .set_entity(&self.settings_observer, &mut cx.to_async()),
1688            self.client
1689                .subscribe_to_entity(project_id)?
1690                .set_entity(&self.git_store, &mut cx.to_async()),
1691        ]);
1692
1693        self.buffer_store.update(cx, |buffer_store, cx| {
1694            buffer_store.shared(project_id, self.client.clone().into(), cx)
1695        });
1696        self.worktree_store.update(cx, |worktree_store, cx| {
1697            worktree_store.shared(project_id, self.client.clone().into(), cx);
1698        });
1699        self.lsp_store.update(cx, |lsp_store, cx| {
1700            lsp_store.shared(project_id, self.client.clone().into(), cx)
1701        });
1702        self.task_store.update(cx, |task_store, cx| {
1703            task_store.shared(project_id, self.client.clone().into(), cx);
1704        });
1705        self.settings_observer.update(cx, |settings_observer, cx| {
1706            settings_observer.shared(project_id, self.client.clone().into(), cx)
1707        });
1708
1709        self.client_state = ProjectClientState::Shared {
1710            remote_id: project_id,
1711        };
1712
1713        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1714        cx.notify();
1715        Ok(())
1716    }
1717
1718    pub fn reshared(
1719        &mut self,
1720        message: proto::ResharedProject,
1721        cx: &mut Context<Self>,
1722    ) -> Result<()> {
1723        self.buffer_store
1724            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
1725        self.set_collaborators_from_proto(message.collaborators, cx)?;
1726
1727        self.worktree_store.update(cx, |worktree_store, cx| {
1728            worktree_store.send_project_updates(cx);
1729        });
1730        cx.notify();
1731        cx.emit(Event::Reshared);
1732        Ok(())
1733    }
1734
1735    pub fn rejoined(
1736        &mut self,
1737        message: proto::RejoinedProject,
1738        message_id: u32,
1739        cx: &mut Context<Self>,
1740    ) -> Result<()> {
1741        cx.update_global::<SettingsStore, _>(|store, cx| {
1742            self.worktree_store.update(cx, |worktree_store, cx| {
1743                for worktree in worktree_store.worktrees() {
1744                    store
1745                        .clear_local_settings(worktree.read(cx).id(), cx)
1746                        .log_err();
1747                }
1748            });
1749        });
1750
1751        self.join_project_response_message_id = message_id;
1752        self.set_worktrees_from_proto(message.worktrees, cx)?;
1753        self.set_collaborators_from_proto(message.collaborators, cx)?;
1754        self.lsp_store.update(cx, |lsp_store, _| {
1755            lsp_store.set_language_server_statuses_from_proto(message.language_servers)
1756        });
1757        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
1758            .unwrap();
1759        cx.emit(Event::Rejoined);
1760        cx.notify();
1761        Ok(())
1762    }
1763
1764    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
1765        self.unshare_internal(cx)?;
1766        cx.notify();
1767        Ok(())
1768    }
1769
1770    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
1771        if self.is_via_collab() {
1772            return Err(anyhow!("attempted to unshare a remote project"));
1773        }
1774
1775        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
1776            self.client_state = ProjectClientState::Local;
1777            self.collaborators.clear();
1778            self.client_subscriptions.clear();
1779            self.worktree_store.update(cx, |store, cx| {
1780                store.unshared(cx);
1781            });
1782            self.buffer_store.update(cx, |buffer_store, cx| {
1783                buffer_store.forget_shared_buffers();
1784                buffer_store.unshared(cx)
1785            });
1786            self.task_store.update(cx, |task_store, cx| {
1787                task_store.unshared(cx);
1788            });
1789            self.settings_observer.update(cx, |settings_observer, cx| {
1790                settings_observer.unshared(cx);
1791            });
1792
1793            self.client
1794                .send(proto::UnshareProject {
1795                    project_id: remote_id,
1796                })
1797                .ok();
1798            Ok(())
1799        } else {
1800            Err(anyhow!("attempted to unshare an unshared project"))
1801        }
1802    }
1803
1804    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
1805        if self.is_disconnected(cx) {
1806            return;
1807        }
1808        self.disconnected_from_host_internal(cx);
1809        cx.emit(Event::DisconnectedFromHost);
1810        cx.notify();
1811    }
1812
1813    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
1814        let new_capability =
1815            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
1816                Capability::ReadWrite
1817            } else {
1818                Capability::ReadOnly
1819            };
1820        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
1821            if *capability == new_capability {
1822                return;
1823            }
1824
1825            *capability = new_capability;
1826            for buffer in self.opened_buffers(cx) {
1827                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
1828            }
1829        }
1830    }
1831
1832    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
1833        if let ProjectClientState::Remote {
1834            sharing_has_stopped,
1835            ..
1836        } = &mut self.client_state
1837        {
1838            *sharing_has_stopped = true;
1839            self.collaborators.clear();
1840            self.worktree_store.update(cx, |store, cx| {
1841                store.disconnected_from_host(cx);
1842            });
1843            self.buffer_store.update(cx, |buffer_store, cx| {
1844                buffer_store.disconnected_from_host(cx)
1845            });
1846            self.lsp_store
1847                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
1848        }
1849    }
1850
1851    pub fn close(&mut self, cx: &mut Context<Self>) {
1852        cx.emit(Event::Closed);
1853    }
1854
1855    pub fn is_disconnected(&self, cx: &App) -> bool {
1856        match &self.client_state {
1857            ProjectClientState::Remote {
1858                sharing_has_stopped,
1859                ..
1860            } => *sharing_has_stopped,
1861            ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
1862            _ => false,
1863        }
1864    }
1865
1866    fn ssh_is_disconnected(&self, cx: &App) -> bool {
1867        self.ssh_client
1868            .as_ref()
1869            .map(|ssh| ssh.read(cx).is_disconnected())
1870            .unwrap_or(false)
1871    }
1872
1873    pub fn capability(&self) -> Capability {
1874        match &self.client_state {
1875            ProjectClientState::Remote { capability, .. } => *capability,
1876            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
1877        }
1878    }
1879
1880    pub fn is_read_only(&self, cx: &App) -> bool {
1881        self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
1882    }
1883
1884    pub fn is_local(&self) -> bool {
1885        match &self.client_state {
1886            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1887                self.ssh_client.is_none()
1888            }
1889            ProjectClientState::Remote { .. } => false,
1890        }
1891    }
1892
1893    pub fn is_via_ssh(&self) -> bool {
1894        match &self.client_state {
1895            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1896                self.ssh_client.is_some()
1897            }
1898            ProjectClientState::Remote { .. } => false,
1899        }
1900    }
1901
1902    pub fn is_via_collab(&self) -> bool {
1903        match &self.client_state {
1904            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
1905            ProjectClientState::Remote { .. } => true,
1906        }
1907    }
1908
1909    pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
1910        self.buffer_store
1911            .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
1912    }
1913
1914    pub fn create_local_buffer(
1915        &mut self,
1916        text: &str,
1917        language: Option<Arc<Language>>,
1918        cx: &mut Context<Self>,
1919    ) -> Entity<Buffer> {
1920        if self.is_via_collab() || self.is_via_ssh() {
1921            panic!("called create_local_buffer on a remote project")
1922        }
1923        self.buffer_store.update(cx, |buffer_store, cx| {
1924            buffer_store.create_local_buffer(text, language, cx)
1925        })
1926    }
1927
1928    pub fn open_path(
1929        &mut self,
1930        path: ProjectPath,
1931        cx: &mut Context<Self>,
1932    ) -> Task<Result<(Option<ProjectEntryId>, AnyEntity)>> {
1933        let task = self.open_buffer(path.clone(), cx);
1934        cx.spawn(move |_, cx| async move {
1935            let buffer = task.await?;
1936            let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1937                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1938            })?;
1939
1940            let buffer: &AnyEntity = &buffer;
1941            Ok((project_entry_id, buffer.clone()))
1942        })
1943    }
1944
1945    pub fn open_local_buffer(
1946        &mut self,
1947        abs_path: impl AsRef<Path>,
1948        cx: &mut Context<Self>,
1949    ) -> Task<Result<Entity<Buffer>>> {
1950        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1951            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1952        } else {
1953            Task::ready(Err(anyhow!("no such path")))
1954        }
1955    }
1956
1957    #[cfg(any(test, feature = "test-support"))]
1958    pub fn open_local_buffer_with_lsp(
1959        &mut self,
1960        abs_path: impl AsRef<Path>,
1961        cx: &mut Context<Self>,
1962    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
1963        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1964            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
1965        } else {
1966            Task::ready(Err(anyhow!("no such path")))
1967        }
1968    }
1969
1970    pub fn open_buffer(
1971        &mut self,
1972        path: impl Into<ProjectPath>,
1973        cx: &mut App,
1974    ) -> Task<Result<Entity<Buffer>>> {
1975        if self.is_disconnected(cx) {
1976            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1977        }
1978
1979        self.buffer_store.update(cx, |buffer_store, cx| {
1980            buffer_store.open_buffer(path.into(), cx)
1981        })
1982    }
1983
1984    #[cfg(any(test, feature = "test-support"))]
1985    pub fn open_buffer_with_lsp(
1986        &mut self,
1987        path: impl Into<ProjectPath>,
1988        cx: &mut Context<Self>,
1989    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
1990        let buffer = self.open_buffer(path, cx);
1991        cx.spawn(|this, mut cx| async move {
1992            let buffer = buffer.await?;
1993            let handle = this.update(&mut cx, |project, cx| {
1994                project.register_buffer_with_language_servers(&buffer, cx)
1995            })?;
1996            Ok((buffer, handle))
1997        })
1998    }
1999
2000    pub fn register_buffer_with_language_servers(
2001        &self,
2002        buffer: &Entity<Buffer>,
2003        cx: &mut App,
2004    ) -> OpenLspBufferHandle {
2005        self.lsp_store.update(cx, |lsp_store, cx| {
2006            lsp_store.register_buffer_with_language_servers(&buffer, false, cx)
2007        })
2008    }
2009
2010    pub fn open_unstaged_diff(
2011        &mut self,
2012        buffer: Entity<Buffer>,
2013        cx: &mut Context<Self>,
2014    ) -> Task<Result<Entity<BufferDiff>>> {
2015        if self.is_disconnected(cx) {
2016            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2017        }
2018
2019        self.buffer_store.update(cx, |buffer_store, cx| {
2020            buffer_store.open_unstaged_diff(buffer, cx)
2021        })
2022    }
2023
2024    pub fn open_uncommitted_diff(
2025        &mut self,
2026        buffer: Entity<Buffer>,
2027        cx: &mut Context<Self>,
2028    ) -> Task<Result<Entity<BufferDiff>>> {
2029        if self.is_disconnected(cx) {
2030            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2031        }
2032
2033        self.buffer_store.update(cx, |buffer_store, cx| {
2034            buffer_store.open_uncommitted_diff(buffer, cx)
2035        })
2036    }
2037
2038    pub fn open_buffer_by_id(
2039        &mut self,
2040        id: BufferId,
2041        cx: &mut Context<Self>,
2042    ) -> Task<Result<Entity<Buffer>>> {
2043        if let Some(buffer) = self.buffer_for_id(id, cx) {
2044            Task::ready(Ok(buffer))
2045        } else if self.is_local() || self.is_via_ssh() {
2046            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
2047        } else if let Some(project_id) = self.remote_id() {
2048            let request = self.client.request(proto::OpenBufferById {
2049                project_id,
2050                id: id.into(),
2051            });
2052            cx.spawn(move |project, mut cx| async move {
2053                let buffer_id = BufferId::new(request.await?.buffer_id)?;
2054                project
2055                    .update(&mut cx, |project, cx| {
2056                        project.buffer_store.update(cx, |buffer_store, cx| {
2057                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
2058                        })
2059                    })?
2060                    .await
2061            })
2062        } else {
2063            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2064        }
2065    }
2066
2067    pub fn save_buffers(
2068        &self,
2069        buffers: HashSet<Entity<Buffer>>,
2070        cx: &mut Context<Self>,
2071    ) -> Task<Result<()>> {
2072        cx.spawn(move |this, mut cx| async move {
2073            let save_tasks = buffers.into_iter().filter_map(|buffer| {
2074                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
2075                    .ok()
2076            });
2077            try_join_all(save_tasks).await?;
2078            Ok(())
2079        })
2080    }
2081
2082    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2083        self.buffer_store
2084            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2085    }
2086
2087    pub fn save_buffer_as(
2088        &mut self,
2089        buffer: Entity<Buffer>,
2090        path: ProjectPath,
2091        cx: &mut Context<Self>,
2092    ) -> Task<Result<()>> {
2093        self.buffer_store.update(cx, |buffer_store, cx| {
2094            buffer_store.save_buffer_as(buffer.clone(), path, cx)
2095        })
2096    }
2097
2098    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2099        self.buffer_store.read(cx).get_by_path(path, cx)
2100    }
2101
2102    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2103        {
2104            let mut remotely_created_models = self.remotely_created_models.lock();
2105            if remotely_created_models.retain_count > 0 {
2106                remotely_created_models.buffers.push(buffer.clone())
2107            }
2108        }
2109
2110        self.request_buffer_diff_recalculation(buffer, cx);
2111
2112        cx.subscribe(buffer, |this, buffer, event, cx| {
2113            this.on_buffer_event(buffer, event, cx);
2114        })
2115        .detach();
2116
2117        Ok(())
2118    }
2119
2120    pub fn open_image(
2121        &mut self,
2122        path: impl Into<ProjectPath>,
2123        cx: &mut Context<Self>,
2124    ) -> Task<Result<Entity<ImageItem>>> {
2125        if self.is_disconnected(cx) {
2126            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2127        }
2128
2129        let open_image_task = self.image_store.update(cx, |image_store, cx| {
2130            image_store.open_image(path.into(), cx)
2131        });
2132
2133        let weak_project = cx.entity().downgrade();
2134        cx.spawn(move |_, mut cx| async move {
2135            let image_item = open_image_task.await?;
2136            let project = weak_project
2137                .upgrade()
2138                .ok_or_else(|| anyhow!("Project dropped"))?;
2139
2140            let metadata =
2141                ImageItem::load_image_metadata(image_item.clone(), project, &mut cx).await?;
2142            image_item.update(&mut cx, |image_item, cx| {
2143                image_item.image_metadata = Some(metadata);
2144                cx.emit(ImageItemEvent::MetadataUpdated);
2145            })?;
2146
2147            Ok(image_item)
2148        })
2149    }
2150
2151    async fn send_buffer_ordered_messages(
2152        this: WeakEntity<Self>,
2153        rx: UnboundedReceiver<BufferOrderedMessage>,
2154        mut cx: AsyncApp,
2155    ) -> Result<()> {
2156        const MAX_BATCH_SIZE: usize = 128;
2157
2158        let mut operations_by_buffer_id = HashMap::default();
2159        async fn flush_operations(
2160            this: &WeakEntity<Project>,
2161            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2162            needs_resync_with_host: &mut bool,
2163            is_local: bool,
2164            cx: &mut AsyncApp,
2165        ) -> Result<()> {
2166            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2167                let request = this.update(cx, |this, _| {
2168                    let project_id = this.remote_id()?;
2169                    Some(this.client.request(proto::UpdateBuffer {
2170                        buffer_id: buffer_id.into(),
2171                        project_id,
2172                        operations,
2173                    }))
2174                })?;
2175                if let Some(request) = request {
2176                    if request.await.is_err() && !is_local {
2177                        *needs_resync_with_host = true;
2178                        break;
2179                    }
2180                }
2181            }
2182            Ok(())
2183        }
2184
2185        let mut needs_resync_with_host = false;
2186        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2187
2188        while let Some(changes) = changes.next().await {
2189            let is_local = this.update(&mut cx, |this, _| this.is_local())?;
2190
2191            for change in changes {
2192                match change {
2193                    BufferOrderedMessage::Operation {
2194                        buffer_id,
2195                        operation,
2196                    } => {
2197                        if needs_resync_with_host {
2198                            continue;
2199                        }
2200
2201                        operations_by_buffer_id
2202                            .entry(buffer_id)
2203                            .or_insert(Vec::new())
2204                            .push(operation);
2205                    }
2206
2207                    BufferOrderedMessage::Resync => {
2208                        operations_by_buffer_id.clear();
2209                        if this
2210                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2211                            .await
2212                            .is_ok()
2213                        {
2214                            needs_resync_with_host = false;
2215                        }
2216                    }
2217
2218                    BufferOrderedMessage::LanguageServerUpdate {
2219                        language_server_id,
2220                        message,
2221                    } => {
2222                        flush_operations(
2223                            &this,
2224                            &mut operations_by_buffer_id,
2225                            &mut needs_resync_with_host,
2226                            is_local,
2227                            &mut cx,
2228                        )
2229                        .await?;
2230
2231                        this.update(&mut cx, |this, _| {
2232                            if let Some(project_id) = this.remote_id() {
2233                                this.client
2234                                    .send(proto::UpdateLanguageServer {
2235                                        project_id,
2236                                        language_server_id: language_server_id.0 as u64,
2237                                        variant: Some(message),
2238                                    })
2239                                    .log_err();
2240                            }
2241                        })?;
2242                    }
2243                }
2244            }
2245
2246            flush_operations(
2247                &this,
2248                &mut operations_by_buffer_id,
2249                &mut needs_resync_with_host,
2250                is_local,
2251                &mut cx,
2252            )
2253            .await?;
2254        }
2255
2256        Ok(())
2257    }
2258
2259    fn on_buffer_store_event(
2260        &mut self,
2261        _: Entity<BufferStore>,
2262        event: &BufferStoreEvent,
2263        cx: &mut Context<Self>,
2264    ) {
2265        match event {
2266            BufferStoreEvent::BufferAdded(buffer) => {
2267                self.register_buffer(buffer, cx).log_err();
2268            }
2269            BufferStoreEvent::BufferChangedFilePath { .. } => {}
2270            BufferStoreEvent::BufferDropped(buffer_id) => {
2271                if let Some(ref ssh_client) = self.ssh_client {
2272                    ssh_client
2273                        .read(cx)
2274                        .proto_client()
2275                        .send(proto::CloseBuffer {
2276                            project_id: 0,
2277                            buffer_id: buffer_id.to_proto(),
2278                        })
2279                        .log_err();
2280                }
2281            }
2282        }
2283    }
2284
2285    fn on_image_store_event(
2286        &mut self,
2287        _: Entity<ImageStore>,
2288        event: &ImageStoreEvent,
2289        cx: &mut Context<Self>,
2290    ) {
2291        match event {
2292            ImageStoreEvent::ImageAdded(image) => {
2293                cx.subscribe(image, |this, image, event, cx| {
2294                    this.on_image_event(image, event, cx);
2295                })
2296                .detach();
2297            }
2298        }
2299    }
2300
2301    fn on_lsp_store_event(
2302        &mut self,
2303        _: Entity<LspStore>,
2304        event: &LspStoreEvent,
2305        cx: &mut Context<Self>,
2306    ) {
2307        match event {
2308            LspStoreEvent::DiagnosticsUpdated {
2309                language_server_id,
2310                path,
2311            } => cx.emit(Event::DiagnosticsUpdated {
2312                path: path.clone(),
2313                language_server_id: *language_server_id,
2314            }),
2315            LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2316                Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2317            ),
2318            LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2319                cx.emit(Event::LanguageServerRemoved(*language_server_id))
2320            }
2321            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2322                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2323            ),
2324            LspStoreEvent::LanguageDetected {
2325                buffer,
2326                new_language,
2327            } => {
2328                let Some(_) = new_language else {
2329                    cx.emit(Event::LanguageNotFound(buffer.clone()));
2330                    return;
2331                };
2332            }
2333            LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2334            LspStoreEvent::LanguageServerPrompt(prompt) => {
2335                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2336            }
2337            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2338                cx.emit(Event::DiskBasedDiagnosticsStarted {
2339                    language_server_id: *language_server_id,
2340                });
2341            }
2342            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2343                cx.emit(Event::DiskBasedDiagnosticsFinished {
2344                    language_server_id: *language_server_id,
2345                });
2346            }
2347            LspStoreEvent::LanguageServerUpdate {
2348                language_server_id,
2349                message,
2350            } => {
2351                if self.is_local() {
2352                    self.enqueue_buffer_ordered_message(
2353                        BufferOrderedMessage::LanguageServerUpdate {
2354                            language_server_id: *language_server_id,
2355                            message: message.clone(),
2356                        },
2357                    )
2358                    .ok();
2359                }
2360            }
2361            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2362                notification_id: "lsp".into(),
2363                message: message.clone(),
2364            }),
2365            LspStoreEvent::SnippetEdit {
2366                buffer_id,
2367                edits,
2368                most_recent_edit,
2369            } => {
2370                if most_recent_edit.replica_id == self.replica_id() {
2371                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2372                }
2373            }
2374        }
2375    }
2376
2377    fn on_ssh_event(
2378        &mut self,
2379        _: Entity<SshRemoteClient>,
2380        event: &remote::SshRemoteEvent,
2381        cx: &mut Context<Self>,
2382    ) {
2383        match event {
2384            remote::SshRemoteEvent::Disconnected => {
2385                // if self.is_via_ssh() {
2386                // self.collaborators.clear();
2387                self.worktree_store.update(cx, |store, cx| {
2388                    store.disconnected_from_host(cx);
2389                });
2390                self.buffer_store.update(cx, |buffer_store, cx| {
2391                    buffer_store.disconnected_from_host(cx)
2392                });
2393                self.lsp_store.update(cx, |lsp_store, _cx| {
2394                    lsp_store.disconnected_from_ssh_remote()
2395                });
2396                cx.emit(Event::DisconnectedFromSshRemote);
2397            }
2398        }
2399    }
2400
2401    fn on_settings_observer_event(
2402        &mut self,
2403        _: Entity<SettingsObserver>,
2404        event: &SettingsObserverEvent,
2405        cx: &mut Context<Self>,
2406    ) {
2407        match event {
2408            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2409                Err(InvalidSettingsError::LocalSettings { message, path }) => {
2410                    let message =
2411                        format!("Failed to set local settings in {:?}:\n{}", path, message);
2412                    cx.emit(Event::Toast {
2413                        notification_id: "local-settings".into(),
2414                        message,
2415                    });
2416                }
2417                Ok(_) => cx.emit(Event::HideToast {
2418                    notification_id: "local-settings".into(),
2419                }),
2420                Err(_) => {}
2421            },
2422        }
2423    }
2424
2425    fn on_worktree_store_event(
2426        &mut self,
2427        _: Entity<WorktreeStore>,
2428        event: &WorktreeStoreEvent,
2429        cx: &mut Context<Self>,
2430    ) {
2431        match event {
2432            WorktreeStoreEvent::WorktreeAdded(worktree) => {
2433                self.on_worktree_added(worktree, cx);
2434                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2435            }
2436            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2437                cx.emit(Event::WorktreeRemoved(*id));
2438            }
2439            WorktreeStoreEvent::WorktreeReleased(_, id) => {
2440                self.on_worktree_released(*id, cx);
2441            }
2442            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2443            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2444            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2445                self.client()
2446                    .telemetry()
2447                    .report_discovered_project_events(*worktree_id, changes);
2448                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2449            }
2450            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(worktree_id) => {
2451                cx.emit(Event::WorktreeUpdatedGitRepositories(*worktree_id))
2452            }
2453            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2454                cx.emit(Event::DeletedEntry(*worktree_id, *id))
2455            }
2456        }
2457    }
2458
2459    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
2460        {
2461            let mut remotely_created_models = self.remotely_created_models.lock();
2462            if remotely_created_models.retain_count > 0 {
2463                remotely_created_models.worktrees.push(worktree.clone())
2464            }
2465        }
2466        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2467        cx.notify();
2468    }
2469
2470    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2471        if let Some(ssh) = &self.ssh_client {
2472            ssh.read(cx)
2473                .proto_client()
2474                .send(proto::RemoveWorktree {
2475                    worktree_id: id_to_remove.to_proto(),
2476                })
2477                .log_err();
2478        }
2479
2480        cx.notify();
2481    }
2482
2483    fn on_buffer_event(
2484        &mut self,
2485        buffer: Entity<Buffer>,
2486        event: &BufferEvent,
2487        cx: &mut Context<Self>,
2488    ) -> Option<()> {
2489        if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2490            self.request_buffer_diff_recalculation(&buffer, cx);
2491        }
2492
2493        let buffer_id = buffer.read(cx).remote_id();
2494        match event {
2495            BufferEvent::ReloadNeeded => {
2496                if !self.is_via_collab() {
2497                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2498                        .detach_and_log_err(cx);
2499                }
2500            }
2501            BufferEvent::Operation {
2502                operation,
2503                is_local: true,
2504            } => {
2505                let operation = language::proto::serialize_operation(operation);
2506
2507                if let Some(ssh) = &self.ssh_client {
2508                    ssh.read(cx)
2509                        .proto_client()
2510                        .send(proto::UpdateBuffer {
2511                            project_id: 0,
2512                            buffer_id: buffer_id.to_proto(),
2513                            operations: vec![operation.clone()],
2514                        })
2515                        .ok();
2516                }
2517
2518                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2519                    buffer_id,
2520                    operation,
2521                })
2522                .ok();
2523            }
2524
2525            _ => {}
2526        }
2527
2528        None
2529    }
2530
2531    fn on_image_event(
2532        &mut self,
2533        image: Entity<ImageItem>,
2534        event: &ImageItemEvent,
2535        cx: &mut Context<Self>,
2536    ) -> Option<()> {
2537        match event {
2538            ImageItemEvent::ReloadNeeded => {
2539                if !self.is_via_collab() {
2540                    self.reload_images([image.clone()].into_iter().collect(), cx)
2541                        .detach_and_log_err(cx);
2542                }
2543            }
2544            _ => {}
2545        }
2546
2547        None
2548    }
2549
2550    fn request_buffer_diff_recalculation(
2551        &mut self,
2552        buffer: &Entity<Buffer>,
2553        cx: &mut Context<Self>,
2554    ) {
2555        self.buffers_needing_diff.insert(buffer.downgrade());
2556        let first_insertion = self.buffers_needing_diff.len() == 1;
2557
2558        let settings = ProjectSettings::get_global(cx);
2559        let delay = if let Some(delay) = settings.git.gutter_debounce {
2560            delay
2561        } else {
2562            if first_insertion {
2563                let this = cx.weak_entity();
2564                cx.defer(move |cx| {
2565                    if let Some(this) = this.upgrade() {
2566                        this.update(cx, |this, cx| {
2567                            this.recalculate_buffer_diffs(cx).detach();
2568                        });
2569                    }
2570                });
2571            }
2572            return;
2573        };
2574
2575        const MIN_DELAY: u64 = 50;
2576        let delay = delay.max(MIN_DELAY);
2577        let duration = Duration::from_millis(delay);
2578
2579        self.git_diff_debouncer
2580            .fire_new(duration, cx, move |this, cx| {
2581                this.recalculate_buffer_diffs(cx)
2582            });
2583    }
2584
2585    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2586        cx.spawn(move |this, mut cx| async move {
2587            loop {
2588                let task = this
2589                    .update(&mut cx, |this, cx| {
2590                        let buffers = this
2591                            .buffers_needing_diff
2592                            .drain()
2593                            .filter_map(|buffer| buffer.upgrade())
2594                            .collect::<Vec<_>>();
2595                        if buffers.is_empty() {
2596                            None
2597                        } else {
2598                            Some(this.buffer_store.update(cx, |buffer_store, cx| {
2599                                buffer_store.recalculate_buffer_diffs(buffers, cx)
2600                            }))
2601                        }
2602                    })
2603                    .ok()
2604                    .flatten();
2605
2606                if let Some(task) = task {
2607                    task.await;
2608                } else {
2609                    break;
2610                }
2611            }
2612        })
2613    }
2614
2615    pub fn set_language_for_buffer(
2616        &mut self,
2617        buffer: &Entity<Buffer>,
2618        new_language: Arc<Language>,
2619        cx: &mut Context<Self>,
2620    ) {
2621        self.lsp_store.update(cx, |lsp_store, cx| {
2622            lsp_store.set_language_for_buffer(buffer, new_language, cx)
2623        })
2624    }
2625
2626    pub fn restart_language_servers_for_buffers(
2627        &mut self,
2628        buffers: Vec<Entity<Buffer>>,
2629        cx: &mut Context<Self>,
2630    ) {
2631        self.lsp_store.update(cx, |lsp_store, cx| {
2632            lsp_store.restart_language_servers_for_buffers(buffers, cx)
2633        })
2634    }
2635
2636    pub fn cancel_language_server_work_for_buffers(
2637        &mut self,
2638        buffers: impl IntoIterator<Item = Entity<Buffer>>,
2639        cx: &mut Context<Self>,
2640    ) {
2641        self.lsp_store.update(cx, |lsp_store, cx| {
2642            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2643        })
2644    }
2645
2646    pub fn cancel_language_server_work(
2647        &mut self,
2648        server_id: LanguageServerId,
2649        token_to_cancel: Option<String>,
2650        cx: &mut Context<Self>,
2651    ) {
2652        self.lsp_store.update(cx, |lsp_store, cx| {
2653            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2654        })
2655    }
2656
2657    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2658        self.buffer_ordered_messages_tx
2659            .unbounded_send(message)
2660            .map_err(|e| anyhow!(e))
2661    }
2662
2663    pub fn available_toolchains(
2664        &self,
2665        worktree_id: WorktreeId,
2666        language_name: LanguageName,
2667        cx: &App,
2668    ) -> Task<Option<ToolchainList>> {
2669        if let Some(toolchain_store) = self.toolchain_store.clone() {
2670            cx.spawn(|cx| async move {
2671                cx.update(|cx| {
2672                    toolchain_store
2673                        .read(cx)
2674                        .list_toolchains(worktree_id, language_name, cx)
2675                })
2676                .ok()?
2677                .await
2678            })
2679        } else {
2680            Task::ready(None)
2681        }
2682    }
2683
2684    pub async fn toolchain_term(
2685        languages: Arc<LanguageRegistry>,
2686        language_name: LanguageName,
2687    ) -> Option<SharedString> {
2688        languages
2689            .language_for_name(language_name.as_ref())
2690            .await
2691            .ok()?
2692            .toolchain_lister()
2693            .map(|lister| lister.term())
2694    }
2695
2696    pub fn activate_toolchain(
2697        &self,
2698        worktree_id: WorktreeId,
2699        toolchain: Toolchain,
2700        cx: &mut App,
2701    ) -> Task<Option<()>> {
2702        let Some(toolchain_store) = self.toolchain_store.clone() else {
2703            return Task::ready(None);
2704        };
2705        toolchain_store.update(cx, |this, cx| {
2706            this.activate_toolchain(worktree_id, toolchain, cx)
2707        })
2708    }
2709    pub fn active_toolchain(
2710        &self,
2711        worktree_id: WorktreeId,
2712        language_name: LanguageName,
2713        cx: &App,
2714    ) -> Task<Option<Toolchain>> {
2715        let Some(toolchain_store) = self.toolchain_store.clone() else {
2716            return Task::ready(None);
2717        };
2718        toolchain_store
2719            .read(cx)
2720            .active_toolchain(worktree_id, language_name, cx)
2721    }
2722    pub fn language_server_statuses<'a>(
2723        &'a self,
2724        cx: &'a App,
2725    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2726        self.lsp_store.read(cx).language_server_statuses()
2727    }
2728
2729    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
2730        self.lsp_store.read(cx).last_formatting_failure()
2731    }
2732
2733    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
2734        self.lsp_store
2735            .update(cx, |store, _| store.reset_last_formatting_failure());
2736    }
2737
2738    pub fn reload_buffers(
2739        &self,
2740        buffers: HashSet<Entity<Buffer>>,
2741        push_to_history: bool,
2742        cx: &mut Context<Self>,
2743    ) -> Task<Result<ProjectTransaction>> {
2744        self.buffer_store.update(cx, |buffer_store, cx| {
2745            buffer_store.reload_buffers(buffers, push_to_history, cx)
2746        })
2747    }
2748
2749    pub fn reload_images(
2750        &self,
2751        images: HashSet<Entity<ImageItem>>,
2752        cx: &mut Context<Self>,
2753    ) -> Task<Result<()>> {
2754        self.image_store
2755            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
2756    }
2757
2758    pub fn format(
2759        &mut self,
2760        buffers: HashSet<Entity<Buffer>>,
2761        target: LspFormatTarget,
2762        push_to_history: bool,
2763        trigger: lsp_store::FormatTrigger,
2764        cx: &mut Context<Project>,
2765    ) -> Task<anyhow::Result<ProjectTransaction>> {
2766        self.lsp_store.update(cx, |lsp_store, cx| {
2767            lsp_store.format(buffers, target, push_to_history, trigger, cx)
2768        })
2769    }
2770
2771    #[inline(never)]
2772    fn definition_impl(
2773        &mut self,
2774        buffer: &Entity<Buffer>,
2775        position: PointUtf16,
2776        cx: &mut Context<Self>,
2777    ) -> Task<Result<Vec<LocationLink>>> {
2778        self.request_lsp(
2779            buffer.clone(),
2780            LanguageServerToQuery::FirstCapable,
2781            GetDefinition { position },
2782            cx,
2783        )
2784    }
2785    pub fn definition<T: ToPointUtf16>(
2786        &mut self,
2787        buffer: &Entity<Buffer>,
2788        position: T,
2789        cx: &mut Context<Self>,
2790    ) -> Task<Result<Vec<LocationLink>>> {
2791        let position = position.to_point_utf16(buffer.read(cx));
2792        self.definition_impl(buffer, position, cx)
2793    }
2794
2795    fn declaration_impl(
2796        &mut self,
2797        buffer: &Entity<Buffer>,
2798        position: PointUtf16,
2799        cx: &mut Context<Self>,
2800    ) -> Task<Result<Vec<LocationLink>>> {
2801        self.request_lsp(
2802            buffer.clone(),
2803            LanguageServerToQuery::FirstCapable,
2804            GetDeclaration { position },
2805            cx,
2806        )
2807    }
2808
2809    pub fn declaration<T: ToPointUtf16>(
2810        &mut self,
2811        buffer: &Entity<Buffer>,
2812        position: T,
2813        cx: &mut Context<Self>,
2814    ) -> Task<Result<Vec<LocationLink>>> {
2815        let position = position.to_point_utf16(buffer.read(cx));
2816        self.declaration_impl(buffer, position, cx)
2817    }
2818
2819    fn type_definition_impl(
2820        &mut self,
2821        buffer: &Entity<Buffer>,
2822        position: PointUtf16,
2823        cx: &mut Context<Self>,
2824    ) -> Task<Result<Vec<LocationLink>>> {
2825        self.request_lsp(
2826            buffer.clone(),
2827            LanguageServerToQuery::FirstCapable,
2828            GetTypeDefinition { position },
2829            cx,
2830        )
2831    }
2832
2833    pub fn type_definition<T: ToPointUtf16>(
2834        &mut self,
2835        buffer: &Entity<Buffer>,
2836        position: T,
2837        cx: &mut Context<Self>,
2838    ) -> Task<Result<Vec<LocationLink>>> {
2839        let position = position.to_point_utf16(buffer.read(cx));
2840        self.type_definition_impl(buffer, position, cx)
2841    }
2842
2843    pub fn implementation<T: ToPointUtf16>(
2844        &mut self,
2845        buffer: &Entity<Buffer>,
2846        position: T,
2847        cx: &mut Context<Self>,
2848    ) -> Task<Result<Vec<LocationLink>>> {
2849        let position = position.to_point_utf16(buffer.read(cx));
2850        self.request_lsp(
2851            buffer.clone(),
2852            LanguageServerToQuery::FirstCapable,
2853            GetImplementation { position },
2854            cx,
2855        )
2856    }
2857
2858    pub fn references<T: ToPointUtf16>(
2859        &mut self,
2860        buffer: &Entity<Buffer>,
2861        position: T,
2862        cx: &mut Context<Self>,
2863    ) -> Task<Result<Vec<Location>>> {
2864        let position = position.to_point_utf16(buffer.read(cx));
2865        self.request_lsp(
2866            buffer.clone(),
2867            LanguageServerToQuery::FirstCapable,
2868            GetReferences { position },
2869            cx,
2870        )
2871    }
2872
2873    fn document_highlights_impl(
2874        &mut self,
2875        buffer: &Entity<Buffer>,
2876        position: PointUtf16,
2877        cx: &mut Context<Self>,
2878    ) -> Task<Result<Vec<DocumentHighlight>>> {
2879        self.request_lsp(
2880            buffer.clone(),
2881            LanguageServerToQuery::FirstCapable,
2882            GetDocumentHighlights { position },
2883            cx,
2884        )
2885    }
2886
2887    pub fn document_highlights<T: ToPointUtf16>(
2888        &mut self,
2889        buffer: &Entity<Buffer>,
2890        position: T,
2891        cx: &mut Context<Self>,
2892    ) -> Task<Result<Vec<DocumentHighlight>>> {
2893        let position = position.to_point_utf16(buffer.read(cx));
2894        self.document_highlights_impl(buffer, position, cx)
2895    }
2896
2897    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
2898        self.lsp_store
2899            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
2900    }
2901
2902    pub fn open_buffer_for_symbol(
2903        &mut self,
2904        symbol: &Symbol,
2905        cx: &mut Context<Self>,
2906    ) -> Task<Result<Entity<Buffer>>> {
2907        self.lsp_store.update(cx, |lsp_store, cx| {
2908            lsp_store.open_buffer_for_symbol(symbol, cx)
2909        })
2910    }
2911
2912    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
2913        let guard = self.retain_remotely_created_models(cx);
2914        let Some(ssh_client) = self.ssh_client.as_ref() else {
2915            return Task::ready(Err(anyhow!("not an ssh project")));
2916        };
2917
2918        let proto_client = ssh_client.read(cx).proto_client();
2919
2920        cx.spawn(|project, mut cx| async move {
2921            let buffer = proto_client
2922                .request(proto::OpenServerSettings {
2923                    project_id: SSH_PROJECT_ID,
2924                })
2925                .await?;
2926
2927            let buffer = project
2928                .update(&mut cx, |project, cx| {
2929                    project.buffer_store.update(cx, |buffer_store, cx| {
2930                        anyhow::Ok(
2931                            buffer_store
2932                                .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
2933                        )
2934                    })
2935                })??
2936                .await;
2937
2938            drop(guard);
2939            buffer
2940        })
2941    }
2942
2943    pub fn open_local_buffer_via_lsp(
2944        &mut self,
2945        abs_path: lsp::Url,
2946        language_server_id: LanguageServerId,
2947        language_server_name: LanguageServerName,
2948        cx: &mut Context<Self>,
2949    ) -> Task<Result<Entity<Buffer>>> {
2950        self.lsp_store.update(cx, |lsp_store, cx| {
2951            lsp_store.open_local_buffer_via_lsp(
2952                abs_path,
2953                language_server_id,
2954                language_server_name,
2955                cx,
2956            )
2957        })
2958    }
2959
2960    pub fn signature_help<T: ToPointUtf16>(
2961        &self,
2962        buffer: &Entity<Buffer>,
2963        position: T,
2964        cx: &mut Context<Self>,
2965    ) -> Task<Vec<SignatureHelp>> {
2966        self.lsp_store.update(cx, |lsp_store, cx| {
2967            lsp_store.signature_help(buffer, position, cx)
2968        })
2969    }
2970
2971    pub fn hover<T: ToPointUtf16>(
2972        &self,
2973        buffer: &Entity<Buffer>,
2974        position: T,
2975        cx: &mut Context<Self>,
2976    ) -> Task<Vec<Hover>> {
2977        let position = position.to_point_utf16(buffer.read(cx));
2978        self.lsp_store
2979            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
2980    }
2981
2982    pub fn linked_edit(
2983        &self,
2984        buffer: &Entity<Buffer>,
2985        position: Anchor,
2986        cx: &mut Context<Self>,
2987    ) -> Task<Result<Vec<Range<Anchor>>>> {
2988        self.lsp_store.update(cx, |lsp_store, cx| {
2989            lsp_store.linked_edit(buffer, position, cx)
2990        })
2991    }
2992
2993    pub fn completions<T: ToOffset + ToPointUtf16>(
2994        &self,
2995        buffer: &Entity<Buffer>,
2996        position: T,
2997        context: CompletionContext,
2998        cx: &mut Context<Self>,
2999    ) -> Task<Result<Vec<Completion>>> {
3000        let position = position.to_point_utf16(buffer.read(cx));
3001        self.lsp_store.update(cx, |lsp_store, cx| {
3002            lsp_store.completions(buffer, position, context, cx)
3003        })
3004    }
3005
3006    pub fn code_actions<T: Clone + ToOffset>(
3007        &mut self,
3008        buffer_handle: &Entity<Buffer>,
3009        range: Range<T>,
3010        kinds: Option<Vec<CodeActionKind>>,
3011        cx: &mut Context<Self>,
3012    ) -> Task<Result<Vec<CodeAction>>> {
3013        let buffer = buffer_handle.read(cx);
3014        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3015        self.lsp_store.update(cx, |lsp_store, cx| {
3016            lsp_store.code_actions(buffer_handle, range, kinds, cx)
3017        })
3018    }
3019
3020    pub fn apply_code_action(
3021        &self,
3022        buffer_handle: Entity<Buffer>,
3023        action: CodeAction,
3024        push_to_history: bool,
3025        cx: &mut Context<Self>,
3026    ) -> Task<Result<ProjectTransaction>> {
3027        self.lsp_store.update(cx, |lsp_store, cx| {
3028            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3029        })
3030    }
3031
3032    fn prepare_rename_impl(
3033        &mut self,
3034        buffer: Entity<Buffer>,
3035        position: PointUtf16,
3036        cx: &mut Context<Self>,
3037    ) -> Task<Result<PrepareRenameResponse>> {
3038        self.request_lsp(
3039            buffer,
3040            LanguageServerToQuery::FirstCapable,
3041            PrepareRename { position },
3042            cx,
3043        )
3044    }
3045    pub fn prepare_rename<T: ToPointUtf16>(
3046        &mut self,
3047        buffer: Entity<Buffer>,
3048        position: T,
3049        cx: &mut Context<Self>,
3050    ) -> Task<Result<PrepareRenameResponse>> {
3051        let position = position.to_point_utf16(buffer.read(cx));
3052        self.prepare_rename_impl(buffer, position, cx)
3053    }
3054
3055    pub fn perform_rename<T: ToPointUtf16>(
3056        &mut self,
3057        buffer: Entity<Buffer>,
3058        position: T,
3059        new_name: String,
3060        cx: &mut Context<Self>,
3061    ) -> Task<Result<ProjectTransaction>> {
3062        let push_to_history = true;
3063        let position = position.to_point_utf16(buffer.read(cx));
3064        self.request_lsp(
3065            buffer,
3066            LanguageServerToQuery::FirstCapable,
3067            PerformRename {
3068                position,
3069                new_name,
3070                push_to_history,
3071            },
3072            cx,
3073        )
3074    }
3075
3076    pub fn on_type_format<T: ToPointUtf16>(
3077        &mut self,
3078        buffer: Entity<Buffer>,
3079        position: T,
3080        trigger: String,
3081        push_to_history: bool,
3082        cx: &mut Context<Self>,
3083    ) -> Task<Result<Option<Transaction>>> {
3084        self.lsp_store.update(cx, |lsp_store, cx| {
3085            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3086        })
3087    }
3088
3089    pub fn inlay_hints<T: ToOffset>(
3090        &mut self,
3091        buffer_handle: Entity<Buffer>,
3092        range: Range<T>,
3093        cx: &mut Context<Self>,
3094    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3095        let buffer = buffer_handle.read(cx);
3096        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3097        self.lsp_store.update(cx, |lsp_store, cx| {
3098            lsp_store.inlay_hints(buffer_handle, range, cx)
3099        })
3100    }
3101
3102    pub fn resolve_inlay_hint(
3103        &self,
3104        hint: InlayHint,
3105        buffer_handle: Entity<Buffer>,
3106        server_id: LanguageServerId,
3107        cx: &mut Context<Self>,
3108    ) -> Task<anyhow::Result<InlayHint>> {
3109        self.lsp_store.update(cx, |lsp_store, cx| {
3110            lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3111        })
3112    }
3113
3114    pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3115        let (result_tx, result_rx) = smol::channel::unbounded();
3116
3117        let matching_buffers_rx = if query.is_opened_only() {
3118            self.sort_search_candidates(&query, cx)
3119        } else {
3120            self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3121        };
3122
3123        cx.spawn(|_, cx| async move {
3124            let mut range_count = 0;
3125            let mut buffer_count = 0;
3126            let mut limit_reached = false;
3127            let query = Arc::new(query);
3128            let mut chunks = matching_buffers_rx.ready_chunks(64);
3129
3130            // Now that we know what paths match the query, we will load at most
3131            // 64 buffers at a time to avoid overwhelming the main thread. For each
3132            // opened buffer, we will spawn a background task that retrieves all the
3133            // ranges in the buffer matched by the query.
3134            let mut chunks = pin!(chunks);
3135            'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3136                let mut chunk_results = Vec::new();
3137                for buffer in matching_buffer_chunk {
3138                    let buffer = buffer.clone();
3139                    let query = query.clone();
3140                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
3141                    chunk_results.push(cx.background_spawn(async move {
3142                        let ranges = query
3143                            .search(&snapshot, None)
3144                            .await
3145                            .iter()
3146                            .map(|range| {
3147                                snapshot.anchor_before(range.start)
3148                                    ..snapshot.anchor_after(range.end)
3149                            })
3150                            .collect::<Vec<_>>();
3151                        anyhow::Ok((buffer, ranges))
3152                    }));
3153                }
3154
3155                let chunk_results = futures::future::join_all(chunk_results).await;
3156                for result in chunk_results {
3157                    if let Some((buffer, ranges)) = result.log_err() {
3158                        range_count += ranges.len();
3159                        buffer_count += 1;
3160                        result_tx
3161                            .send(SearchResult::Buffer { buffer, ranges })
3162                            .await?;
3163                        if buffer_count > MAX_SEARCH_RESULT_FILES
3164                            || range_count > MAX_SEARCH_RESULT_RANGES
3165                        {
3166                            limit_reached = true;
3167                            break 'outer;
3168                        }
3169                    }
3170                }
3171            }
3172
3173            if limit_reached {
3174                result_tx.send(SearchResult::LimitReached).await?;
3175            }
3176
3177            anyhow::Ok(())
3178        })
3179        .detach();
3180
3181        result_rx
3182    }
3183
3184    fn find_search_candidate_buffers(
3185        &mut self,
3186        query: &SearchQuery,
3187        limit: usize,
3188        cx: &mut Context<Project>,
3189    ) -> Receiver<Entity<Buffer>> {
3190        if self.is_local() {
3191            let fs = self.fs.clone();
3192            self.buffer_store.update(cx, |buffer_store, cx| {
3193                buffer_store.find_search_candidates(query, limit, fs, cx)
3194            })
3195        } else {
3196            self.find_search_candidates_remote(query, limit, cx)
3197        }
3198    }
3199
3200    fn sort_search_candidates(
3201        &mut self,
3202        search_query: &SearchQuery,
3203        cx: &mut Context<Project>,
3204    ) -> Receiver<Entity<Buffer>> {
3205        let worktree_store = self.worktree_store.read(cx);
3206        let mut buffers = search_query
3207            .buffers()
3208            .into_iter()
3209            .flatten()
3210            .filter(|buffer| {
3211                let b = buffer.read(cx);
3212                if let Some(file) = b.file() {
3213                    if !search_query.file_matches(file.path()) {
3214                        return false;
3215                    }
3216                    if let Some(entry) = b
3217                        .entry_id(cx)
3218                        .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3219                    {
3220                        if entry.is_ignored && !search_query.include_ignored() {
3221                            return false;
3222                        }
3223                    }
3224                }
3225                true
3226            })
3227            .collect::<Vec<_>>();
3228        let (tx, rx) = smol::channel::unbounded();
3229        buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3230            (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3231            (None, Some(_)) => std::cmp::Ordering::Less,
3232            (Some(_), None) => std::cmp::Ordering::Greater,
3233            (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3234        });
3235        for buffer in buffers {
3236            tx.send_blocking(buffer.clone()).unwrap()
3237        }
3238
3239        rx
3240    }
3241
3242    fn find_search_candidates_remote(
3243        &mut self,
3244        query: &SearchQuery,
3245        limit: usize,
3246        cx: &mut Context<Project>,
3247    ) -> Receiver<Entity<Buffer>> {
3248        let (tx, rx) = smol::channel::unbounded();
3249
3250        let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3251            (ssh_client.read(cx).proto_client(), 0)
3252        } else if let Some(remote_id) = self.remote_id() {
3253            (self.client.clone().into(), remote_id)
3254        } else {
3255            return rx;
3256        };
3257
3258        let request = client.request(proto::FindSearchCandidates {
3259            project_id: remote_id,
3260            query: Some(query.to_proto()),
3261            limit: limit as _,
3262        });
3263        let guard = self.retain_remotely_created_models(cx);
3264
3265        cx.spawn(move |project, mut cx| async move {
3266            let response = request.await?;
3267            for buffer_id in response.buffer_ids {
3268                let buffer_id = BufferId::new(buffer_id)?;
3269                let buffer = project
3270                    .update(&mut cx, |project, cx| {
3271                        project.buffer_store.update(cx, |buffer_store, cx| {
3272                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
3273                        })
3274                    })?
3275                    .await?;
3276                let _ = tx.send(buffer).await;
3277            }
3278
3279            drop(guard);
3280            anyhow::Ok(())
3281        })
3282        .detach_and_log_err(cx);
3283        rx
3284    }
3285
3286    pub fn request_lsp<R: LspCommand>(
3287        &mut self,
3288        buffer_handle: Entity<Buffer>,
3289        server: LanguageServerToQuery,
3290        request: R,
3291        cx: &mut Context<Self>,
3292    ) -> Task<Result<R::Response>>
3293    where
3294        <R::LspRequest as lsp::request::Request>::Result: Send,
3295        <R::LspRequest as lsp::request::Request>::Params: Send,
3296    {
3297        let guard = self.retain_remotely_created_models(cx);
3298        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3299            lsp_store.request_lsp(buffer_handle, server, request, cx)
3300        });
3301        cx.spawn(|_, _| async move {
3302            let result = task.await;
3303            drop(guard);
3304            result
3305        })
3306    }
3307
3308    /// Move a worktree to a new position in the worktree order.
3309    ///
3310    /// The worktree will moved to the opposite side of the destination worktree.
3311    ///
3312    /// # Example
3313    ///
3314    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3315    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3316    ///
3317    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3318    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3319    ///
3320    /// # Errors
3321    ///
3322    /// An error will be returned if the worktree or destination worktree are not found.
3323    pub fn move_worktree(
3324        &mut self,
3325        source: WorktreeId,
3326        destination: WorktreeId,
3327        cx: &mut Context<'_, Self>,
3328    ) -> Result<()> {
3329        self.worktree_store.update(cx, |worktree_store, cx| {
3330            worktree_store.move_worktree(source, destination, cx)
3331        })
3332    }
3333
3334    pub fn find_or_create_worktree(
3335        &mut self,
3336        abs_path: impl AsRef<Path>,
3337        visible: bool,
3338        cx: &mut Context<Self>,
3339    ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3340        self.worktree_store.update(cx, |worktree_store, cx| {
3341            worktree_store.find_or_create_worktree(abs_path, visible, cx)
3342        })
3343    }
3344
3345    pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3346        self.worktree_store.read_with(cx, |worktree_store, cx| {
3347            worktree_store.find_worktree(abs_path, cx)
3348        })
3349    }
3350
3351    pub fn is_shared(&self) -> bool {
3352        match &self.client_state {
3353            ProjectClientState::Shared { .. } => true,
3354            ProjectClientState::Local => false,
3355            ProjectClientState::Remote { .. } => true,
3356        }
3357    }
3358
3359    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3360    pub fn resolve_path_in_buffer(
3361        &self,
3362        path: &str,
3363        buffer: &Entity<Buffer>,
3364        cx: &mut Context<Self>,
3365    ) -> Task<Option<ResolvedPath>> {
3366        let path_buf = PathBuf::from(path);
3367        if path_buf.is_absolute() || path.starts_with("~") {
3368            self.resolve_abs_path(path, cx)
3369        } else {
3370            self.resolve_path_in_worktrees(path_buf, buffer, cx)
3371        }
3372    }
3373
3374    pub fn resolve_abs_file_path(
3375        &self,
3376        path: &str,
3377        cx: &mut Context<Self>,
3378    ) -> Task<Option<ResolvedPath>> {
3379        let resolve_task = self.resolve_abs_path(path, cx);
3380        cx.background_spawn(async move {
3381            let resolved_path = resolve_task.await;
3382            resolved_path.filter(|path| path.is_file())
3383        })
3384    }
3385
3386    pub fn resolve_abs_path(
3387        &self,
3388        path: &str,
3389        cx: &mut Context<Self>,
3390    ) -> Task<Option<ResolvedPath>> {
3391        if self.is_local() {
3392            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3393            let fs = self.fs.clone();
3394            cx.background_spawn(async move {
3395                let path = expanded.as_path();
3396                let metadata = fs.metadata(path).await.ok().flatten();
3397
3398                metadata.map(|metadata| ResolvedPath::AbsPath {
3399                    path: expanded,
3400                    is_dir: metadata.is_dir,
3401                })
3402            })
3403        } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3404            let request_path = Path::new(path);
3405            let request = ssh_client
3406                .read(cx)
3407                .proto_client()
3408                .request(proto::GetPathMetadata {
3409                    project_id: SSH_PROJECT_ID,
3410                    path: request_path.to_proto(),
3411                });
3412            cx.background_spawn(async move {
3413                let response = request.await.log_err()?;
3414                if response.exists {
3415                    Some(ResolvedPath::AbsPath {
3416                        path: PathBuf::from_proto(response.path),
3417                        is_dir: response.is_dir,
3418                    })
3419                } else {
3420                    None
3421                }
3422            })
3423        } else {
3424            return Task::ready(None);
3425        }
3426    }
3427
3428    fn resolve_path_in_worktrees(
3429        &self,
3430        path: PathBuf,
3431        buffer: &Entity<Buffer>,
3432        cx: &mut Context<Self>,
3433    ) -> Task<Option<ResolvedPath>> {
3434        let mut candidates = vec![path.clone()];
3435
3436        if let Some(file) = buffer.read(cx).file() {
3437            if let Some(dir) = file.path().parent() {
3438                let joined = dir.to_path_buf().join(path);
3439                candidates.push(joined);
3440            }
3441        }
3442
3443        let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3444        cx.spawn(|_, mut cx| async move {
3445            for worktree in worktrees {
3446                for candidate in candidates.iter() {
3447                    let path = worktree
3448                        .update(&mut cx, |worktree, _| {
3449                            let root_entry_path = &worktree.root_entry()?.path;
3450
3451                            let resolved = resolve_path(root_entry_path, candidate);
3452
3453                            let stripped =
3454                                resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3455
3456                            worktree.entry_for_path(stripped).map(|entry| {
3457                                let project_path = ProjectPath {
3458                                    worktree_id: worktree.id(),
3459                                    path: entry.path.clone(),
3460                                };
3461                                ResolvedPath::ProjectPath {
3462                                    project_path,
3463                                    is_dir: entry.is_dir(),
3464                                }
3465                            })
3466                        })
3467                        .ok()?;
3468
3469                    if path.is_some() {
3470                        return path;
3471                    }
3472                }
3473            }
3474            None
3475        })
3476    }
3477
3478    pub fn list_directory(
3479        &self,
3480        query: String,
3481        cx: &mut Context<Self>,
3482    ) -> Task<Result<Vec<PathBuf>>> {
3483        if self.is_local() {
3484            DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3485        } else if let Some(session) = self.ssh_client.as_ref() {
3486            let path_buf = PathBuf::from(query);
3487            let request = proto::ListRemoteDirectory {
3488                dev_server_id: SSH_PROJECT_ID,
3489                path: path_buf.to_proto(),
3490            };
3491
3492            let response = session.read(cx).proto_client().request(request);
3493            cx.background_spawn(async move {
3494                let response = response.await?;
3495                Ok(response.entries.into_iter().map(PathBuf::from).collect())
3496            })
3497        } else {
3498            Task::ready(Err(anyhow!("cannot list directory in remote project")))
3499        }
3500    }
3501
3502    pub fn create_worktree(
3503        &mut self,
3504        abs_path: impl AsRef<Path>,
3505        visible: bool,
3506        cx: &mut Context<Self>,
3507    ) -> Task<Result<Entity<Worktree>>> {
3508        self.worktree_store.update(cx, |worktree_store, cx| {
3509            worktree_store.create_worktree(abs_path, visible, cx)
3510        })
3511    }
3512
3513    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3514        self.worktree_store.update(cx, |worktree_store, cx| {
3515            worktree_store.remove_worktree(id_to_remove, cx);
3516        });
3517    }
3518
3519    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
3520        self.worktree_store.update(cx, |worktree_store, cx| {
3521            worktree_store.add(worktree, cx);
3522        });
3523    }
3524
3525    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
3526        let new_active_entry = entry.and_then(|project_path| {
3527            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3528            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3529            Some(entry.id)
3530        });
3531        if new_active_entry != self.active_entry {
3532            self.active_entry = new_active_entry;
3533            self.lsp_store.update(cx, |lsp_store, _| {
3534                lsp_store.set_active_entry(new_active_entry);
3535            });
3536            cx.emit(Event::ActiveEntryChanged(new_active_entry));
3537        }
3538    }
3539
3540    pub fn language_servers_running_disk_based_diagnostics<'a>(
3541        &'a self,
3542        cx: &'a App,
3543    ) -> impl Iterator<Item = LanguageServerId> + 'a {
3544        self.lsp_store
3545            .read(cx)
3546            .language_servers_running_disk_based_diagnostics()
3547    }
3548
3549    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
3550        self.lsp_store
3551            .read(cx)
3552            .diagnostic_summary(include_ignored, cx)
3553    }
3554
3555    pub fn diagnostic_summaries<'a>(
3556        &'a self,
3557        include_ignored: bool,
3558        cx: &'a App,
3559    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3560        self.lsp_store
3561            .read(cx)
3562            .diagnostic_summaries(include_ignored, cx)
3563    }
3564
3565    pub fn active_entry(&self) -> Option<ProjectEntryId> {
3566        self.active_entry
3567    }
3568
3569    pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
3570        self.worktree_store.read(cx).entry_for_path(path, cx)
3571    }
3572
3573    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
3574        let worktree = self.worktree_for_entry(entry_id, cx)?;
3575        let worktree = worktree.read(cx);
3576        let worktree_id = worktree.id();
3577        let path = worktree.entry_for_id(entry_id)?.path.clone();
3578        Some(ProjectPath { worktree_id, path })
3579    }
3580
3581    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
3582        self.worktree_for_id(project_path.worktree_id, cx)?
3583            .read(cx)
3584            .absolutize(&project_path.path)
3585            .ok()
3586    }
3587
3588    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3589    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3590    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3591    /// the first visible worktree that has an entry for that relative path.
3592    ///
3593    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3594    /// root name from paths.
3595    ///
3596    /// # Arguments
3597    ///
3598    /// * `path` - A full path that starts with a worktree root name, or alternatively a
3599    ///            relative path within a visible worktree.
3600    /// * `cx` - A reference to the `AppContext`.
3601    ///
3602    /// # Returns
3603    ///
3604    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
3605    pub fn find_project_path(&self, path: &Path, cx: &App) -> Option<ProjectPath> {
3606        let worktree_store = self.worktree_store.read(cx);
3607
3608        for worktree in worktree_store.visible_worktrees(cx) {
3609            let worktree_root_name = worktree.read(cx).root_name();
3610            if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
3611                return Some(ProjectPath {
3612                    worktree_id: worktree.read(cx).id(),
3613                    path: relative_path.into(),
3614                });
3615            }
3616        }
3617
3618        for worktree in worktree_store.visible_worktrees(cx) {
3619            let worktree = worktree.read(cx);
3620            if let Some(entry) = worktree.entry_for_path(path) {
3621                return Some(ProjectPath {
3622                    worktree_id: worktree.id(),
3623                    path: entry.path.clone(),
3624                });
3625            }
3626        }
3627
3628        None
3629    }
3630
3631    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
3632        Some(
3633            self.worktree_for_id(project_path.worktree_id, cx)?
3634                .read(cx)
3635                .abs_path()
3636                .to_path_buf(),
3637        )
3638    }
3639
3640    pub fn get_first_worktree_root_repo(&self, cx: &App) -> Option<Arc<dyn GitRepository>> {
3641        let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
3642        let root_entry = worktree.root_git_entry()?;
3643        worktree.get_local_repo(&root_entry)?.repo().clone().into()
3644    }
3645
3646    pub fn branches(&self, project_path: ProjectPath, cx: &App) -> Task<Result<Vec<Branch>>> {
3647        self.worktree_store().read(cx).branches(project_path, cx)
3648    }
3649
3650    pub fn update_or_create_branch(
3651        &self,
3652        repository: ProjectPath,
3653        new_branch: String,
3654        cx: &App,
3655    ) -> Task<Result<()>> {
3656        self.worktree_store()
3657            .read(cx)
3658            .update_or_create_branch(repository, new_branch, cx)
3659    }
3660
3661    pub fn blame_buffer(
3662        &self,
3663        buffer: &Entity<Buffer>,
3664        version: Option<clock::Global>,
3665        cx: &App,
3666    ) -> Task<Result<Option<Blame>>> {
3667        self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
3668    }
3669
3670    pub fn get_permalink_to_line(
3671        &self,
3672        buffer: &Entity<Buffer>,
3673        selection: Range<u32>,
3674        cx: &App,
3675    ) -> Task<Result<url::Url>> {
3676        self.buffer_store
3677            .read(cx)
3678            .get_permalink_to_line(buffer, selection, cx)
3679    }
3680
3681    // RPC message handlers
3682
3683    async fn handle_unshare_project(
3684        this: Entity<Self>,
3685        _: TypedEnvelope<proto::UnshareProject>,
3686        mut cx: AsyncApp,
3687    ) -> Result<()> {
3688        this.update(&mut cx, |this, cx| {
3689            if this.is_local() || this.is_via_ssh() {
3690                this.unshare(cx)?;
3691            } else {
3692                this.disconnected_from_host(cx);
3693            }
3694            Ok(())
3695        })?
3696    }
3697
3698    async fn handle_add_collaborator(
3699        this: Entity<Self>,
3700        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3701        mut cx: AsyncApp,
3702    ) -> Result<()> {
3703        let collaborator = envelope
3704            .payload
3705            .collaborator
3706            .take()
3707            .ok_or_else(|| anyhow!("empty collaborator"))?;
3708
3709        let collaborator = Collaborator::from_proto(collaborator)?;
3710        this.update(&mut cx, |this, cx| {
3711            this.buffer_store.update(cx, |buffer_store, _| {
3712                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
3713            });
3714            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
3715            this.collaborators
3716                .insert(collaborator.peer_id, collaborator);
3717            cx.notify();
3718        })?;
3719
3720        Ok(())
3721    }
3722
3723    async fn handle_update_project_collaborator(
3724        this: Entity<Self>,
3725        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
3726        mut cx: AsyncApp,
3727    ) -> Result<()> {
3728        let old_peer_id = envelope
3729            .payload
3730            .old_peer_id
3731            .ok_or_else(|| anyhow!("missing old peer id"))?;
3732        let new_peer_id = envelope
3733            .payload
3734            .new_peer_id
3735            .ok_or_else(|| anyhow!("missing new peer id"))?;
3736        this.update(&mut cx, |this, cx| {
3737            let collaborator = this
3738                .collaborators
3739                .remove(&old_peer_id)
3740                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
3741            let is_host = collaborator.is_host;
3742            this.collaborators.insert(new_peer_id, collaborator);
3743
3744            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
3745            this.buffer_store.update(cx, |buffer_store, _| {
3746                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
3747            });
3748
3749            if is_host {
3750                this.buffer_store
3751                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
3752                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
3753                    .unwrap();
3754                cx.emit(Event::HostReshared);
3755            }
3756
3757            cx.emit(Event::CollaboratorUpdated {
3758                old_peer_id,
3759                new_peer_id,
3760            });
3761            cx.notify();
3762            Ok(())
3763        })?
3764    }
3765
3766    async fn handle_remove_collaborator(
3767        this: Entity<Self>,
3768        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3769        mut cx: AsyncApp,
3770    ) -> Result<()> {
3771        this.update(&mut cx, |this, cx| {
3772            let peer_id = envelope
3773                .payload
3774                .peer_id
3775                .ok_or_else(|| anyhow!("invalid peer id"))?;
3776            let replica_id = this
3777                .collaborators
3778                .remove(&peer_id)
3779                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3780                .replica_id;
3781            this.buffer_store.update(cx, |buffer_store, cx| {
3782                buffer_store.forget_shared_buffers_for(&peer_id);
3783                for buffer in buffer_store.buffers() {
3784                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3785                }
3786            });
3787
3788            cx.emit(Event::CollaboratorLeft(peer_id));
3789            cx.notify();
3790            Ok(())
3791        })?
3792    }
3793
3794    async fn handle_update_project(
3795        this: Entity<Self>,
3796        envelope: TypedEnvelope<proto::UpdateProject>,
3797        mut cx: AsyncApp,
3798    ) -> Result<()> {
3799        this.update(&mut cx, |this, cx| {
3800            // Don't handle messages that were sent before the response to us joining the project
3801            if envelope.message_id > this.join_project_response_message_id {
3802                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
3803            }
3804            Ok(())
3805        })?
3806    }
3807
3808    async fn handle_toast(
3809        this: Entity<Self>,
3810        envelope: TypedEnvelope<proto::Toast>,
3811        mut cx: AsyncApp,
3812    ) -> Result<()> {
3813        this.update(&mut cx, |_, cx| {
3814            cx.emit(Event::Toast {
3815                notification_id: envelope.payload.notification_id.into(),
3816                message: envelope.payload.message,
3817            });
3818            Ok(())
3819        })?
3820    }
3821
3822    async fn handle_language_server_prompt_request(
3823        this: Entity<Self>,
3824        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
3825        mut cx: AsyncApp,
3826    ) -> Result<proto::LanguageServerPromptResponse> {
3827        let (tx, mut rx) = smol::channel::bounded(1);
3828        let actions: Vec<_> = envelope
3829            .payload
3830            .actions
3831            .into_iter()
3832            .map(|action| MessageActionItem {
3833                title: action,
3834                properties: Default::default(),
3835            })
3836            .collect();
3837        this.update(&mut cx, |_, cx| {
3838            cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
3839                level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
3840                message: envelope.payload.message,
3841                actions: actions.clone(),
3842                lsp_name: envelope.payload.lsp_name,
3843                response_channel: tx,
3844            }));
3845
3846            anyhow::Ok(())
3847        })??;
3848
3849        // We drop `this` to avoid holding a reference in this future for too
3850        // long.
3851        // If we keep the reference, we might not drop the `Project` early
3852        // enough when closing a window and it will only get releases on the
3853        // next `flush_effects()` call.
3854        drop(this);
3855
3856        let mut rx = pin!(rx);
3857        let answer = rx.next().await;
3858
3859        Ok(LanguageServerPromptResponse {
3860            action_response: answer.and_then(|answer| {
3861                actions
3862                    .iter()
3863                    .position(|action| *action == answer)
3864                    .map(|index| index as u64)
3865            }),
3866        })
3867    }
3868
3869    async fn handle_hide_toast(
3870        this: Entity<Self>,
3871        envelope: TypedEnvelope<proto::HideToast>,
3872        mut cx: AsyncApp,
3873    ) -> Result<()> {
3874        this.update(&mut cx, |_, cx| {
3875            cx.emit(Event::HideToast {
3876                notification_id: envelope.payload.notification_id.into(),
3877            });
3878            Ok(())
3879        })?
3880    }
3881
3882    // Collab sends UpdateWorktree protos as messages
3883    async fn handle_update_worktree(
3884        this: Entity<Self>,
3885        envelope: TypedEnvelope<proto::UpdateWorktree>,
3886        mut cx: AsyncApp,
3887    ) -> Result<()> {
3888        this.update(&mut cx, |this, cx| {
3889            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3890            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3891                worktree.update(cx, |worktree, _| {
3892                    let worktree = worktree.as_remote_mut().unwrap();
3893                    worktree.update_from_remote(envelope.payload);
3894                });
3895            }
3896            Ok(())
3897        })?
3898    }
3899
3900    async fn handle_update_buffer_from_ssh(
3901        this: Entity<Self>,
3902        envelope: TypedEnvelope<proto::UpdateBuffer>,
3903        cx: AsyncApp,
3904    ) -> Result<proto::Ack> {
3905        let buffer_store = this.read_with(&cx, |this, cx| {
3906            if let Some(remote_id) = this.remote_id() {
3907                let mut payload = envelope.payload.clone();
3908                payload.project_id = remote_id;
3909                cx.background_spawn(this.client.request(payload))
3910                    .detach_and_log_err(cx);
3911            }
3912            this.buffer_store.clone()
3913        })?;
3914        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3915    }
3916
3917    async fn handle_update_buffer(
3918        this: Entity<Self>,
3919        envelope: TypedEnvelope<proto::UpdateBuffer>,
3920        cx: AsyncApp,
3921    ) -> Result<proto::Ack> {
3922        let buffer_store = this.read_with(&cx, |this, cx| {
3923            if let Some(ssh) = &this.ssh_client {
3924                let mut payload = envelope.payload.clone();
3925                payload.project_id = SSH_PROJECT_ID;
3926                cx.background_spawn(ssh.read(cx).proto_client().request(payload))
3927                    .detach_and_log_err(cx);
3928            }
3929            this.buffer_store.clone()
3930        })?;
3931        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3932    }
3933
3934    fn retain_remotely_created_models(
3935        &mut self,
3936        cx: &mut Context<Self>,
3937    ) -> RemotelyCreatedModelGuard {
3938        {
3939            let mut remotely_create_models = self.remotely_created_models.lock();
3940            if remotely_create_models.retain_count == 0 {
3941                remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
3942                remotely_create_models.worktrees =
3943                    self.worktree_store.read(cx).worktrees().collect();
3944            }
3945            remotely_create_models.retain_count += 1;
3946        }
3947        RemotelyCreatedModelGuard {
3948            remote_models: Arc::downgrade(&self.remotely_created_models),
3949        }
3950    }
3951
3952    async fn handle_create_buffer_for_peer(
3953        this: Entity<Self>,
3954        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
3955        mut cx: AsyncApp,
3956    ) -> Result<()> {
3957        this.update(&mut cx, |this, cx| {
3958            this.buffer_store.update(cx, |buffer_store, cx| {
3959                buffer_store.handle_create_buffer_for_peer(
3960                    envelope,
3961                    this.replica_id(),
3962                    this.capability(),
3963                    cx,
3964                )
3965            })
3966        })?
3967    }
3968
3969    async fn handle_synchronize_buffers(
3970        this: Entity<Self>,
3971        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
3972        mut cx: AsyncApp,
3973    ) -> Result<proto::SynchronizeBuffersResponse> {
3974        let response = this.update(&mut cx, |this, cx| {
3975            let client = this.client.clone();
3976            this.buffer_store.update(cx, |this, cx| {
3977                this.handle_synchronize_buffers(envelope, cx, client)
3978            })
3979        })??;
3980
3981        Ok(response)
3982    }
3983
3984    async fn handle_search_candidate_buffers(
3985        this: Entity<Self>,
3986        envelope: TypedEnvelope<proto::FindSearchCandidates>,
3987        mut cx: AsyncApp,
3988    ) -> Result<proto::FindSearchCandidatesResponse> {
3989        let peer_id = envelope.original_sender_id()?;
3990        let message = envelope.payload;
3991        let query = SearchQuery::from_proto(
3992            message
3993                .query
3994                .ok_or_else(|| anyhow!("missing query field"))?,
3995        )?;
3996        let results = this.update(&mut cx, |this, cx| {
3997            this.find_search_candidate_buffers(&query, message.limit as _, cx)
3998        })?;
3999
4000        let mut response = proto::FindSearchCandidatesResponse {
4001            buffer_ids: Vec::new(),
4002        };
4003
4004        while let Ok(buffer) = results.recv().await {
4005            this.update(&mut cx, |this, cx| {
4006                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4007                response.buffer_ids.push(buffer_id.to_proto());
4008            })?;
4009        }
4010
4011        Ok(response)
4012    }
4013
4014    async fn handle_open_buffer_by_id(
4015        this: Entity<Self>,
4016        envelope: TypedEnvelope<proto::OpenBufferById>,
4017        mut cx: AsyncApp,
4018    ) -> Result<proto::OpenBufferResponse> {
4019        let peer_id = envelope.original_sender_id()?;
4020        let buffer_id = BufferId::new(envelope.payload.id)?;
4021        let buffer = this
4022            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4023            .await?;
4024        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4025    }
4026
4027    async fn handle_open_buffer_by_path(
4028        this: Entity<Self>,
4029        envelope: TypedEnvelope<proto::OpenBufferByPath>,
4030        mut cx: AsyncApp,
4031    ) -> Result<proto::OpenBufferResponse> {
4032        let peer_id = envelope.original_sender_id()?;
4033        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4034        let open_buffer = this.update(&mut cx, |this, cx| {
4035            this.open_buffer(
4036                ProjectPath {
4037                    worktree_id,
4038                    path: Arc::<Path>::from_proto(envelope.payload.path),
4039                },
4040                cx,
4041            )
4042        })?;
4043
4044        let buffer = open_buffer.await?;
4045        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4046    }
4047
4048    async fn handle_open_new_buffer(
4049        this: Entity<Self>,
4050        envelope: TypedEnvelope<proto::OpenNewBuffer>,
4051        mut cx: AsyncApp,
4052    ) -> Result<proto::OpenBufferResponse> {
4053        let buffer = this
4054            .update(&mut cx, |this, cx| this.create_buffer(cx))?
4055            .await?;
4056        let peer_id = envelope.original_sender_id()?;
4057
4058        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4059    }
4060
4061    fn respond_to_open_buffer_request(
4062        this: Entity<Self>,
4063        buffer: Entity<Buffer>,
4064        peer_id: proto::PeerId,
4065        cx: &mut AsyncApp,
4066    ) -> Result<proto::OpenBufferResponse> {
4067        this.update(cx, |this, cx| {
4068            let is_private = buffer
4069                .read(cx)
4070                .file()
4071                .map(|f| f.is_private())
4072                .unwrap_or_default();
4073            if is_private {
4074                Err(anyhow!(ErrorCode::UnsharedItem))
4075            } else {
4076                Ok(proto::OpenBufferResponse {
4077                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4078                })
4079            }
4080        })?
4081    }
4082
4083    fn create_buffer_for_peer(
4084        &mut self,
4085        buffer: &Entity<Buffer>,
4086        peer_id: proto::PeerId,
4087        cx: &mut App,
4088    ) -> BufferId {
4089        self.buffer_store
4090            .update(cx, |buffer_store, cx| {
4091                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4092            })
4093            .detach_and_log_err(cx);
4094        buffer.read(cx).remote_id()
4095    }
4096
4097    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4098        let project_id = match self.client_state {
4099            ProjectClientState::Remote {
4100                sharing_has_stopped,
4101                remote_id,
4102                ..
4103            } => {
4104                if sharing_has_stopped {
4105                    return Task::ready(Err(anyhow!(
4106                        "can't synchronize remote buffers on a readonly project"
4107                    )));
4108                } else {
4109                    remote_id
4110                }
4111            }
4112            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4113                return Task::ready(Err(anyhow!(
4114                    "can't synchronize remote buffers on a local project"
4115                )))
4116            }
4117        };
4118
4119        let client = self.client.clone();
4120        cx.spawn(move |this, mut cx| async move {
4121            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
4122                this.buffer_store.read(cx).buffer_version_info(cx)
4123            })?;
4124            let response = client
4125                .request(proto::SynchronizeBuffers {
4126                    project_id,
4127                    buffers,
4128                })
4129                .await?;
4130
4131            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
4132                response
4133                    .buffers
4134                    .into_iter()
4135                    .map(|buffer| {
4136                        let client = client.clone();
4137                        let buffer_id = match BufferId::new(buffer.id) {
4138                            Ok(id) => id,
4139                            Err(e) => {
4140                                return Task::ready(Err(e));
4141                            }
4142                        };
4143                        let remote_version = language::proto::deserialize_version(&buffer.version);
4144                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4145                            let operations =
4146                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
4147                            cx.background_spawn(async move {
4148                                let operations = operations.await;
4149                                for chunk in split_operations(operations) {
4150                                    client
4151                                        .request(proto::UpdateBuffer {
4152                                            project_id,
4153                                            buffer_id: buffer_id.into(),
4154                                            operations: chunk,
4155                                        })
4156                                        .await?;
4157                                }
4158                                anyhow::Ok(())
4159                            })
4160                        } else {
4161                            Task::ready(Ok(()))
4162                        }
4163                    })
4164                    .collect::<Vec<_>>()
4165            })?;
4166
4167            // Any incomplete buffers have open requests waiting. Request that the host sends
4168            // creates these buffers for us again to unblock any waiting futures.
4169            for id in incomplete_buffer_ids {
4170                cx.background_spawn(client.request(proto::OpenBufferById {
4171                    project_id,
4172                    id: id.into(),
4173                }))
4174                .detach();
4175            }
4176
4177            futures::future::join_all(send_updates_for_buffers)
4178                .await
4179                .into_iter()
4180                .collect()
4181        })
4182    }
4183
4184    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4185        self.worktree_store.read(cx).worktree_metadata_protos(cx)
4186    }
4187
4188    /// Iterator of all open buffers that have unsaved changes
4189    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4190        self.buffer_store.read(cx).buffers().filter_map(|buf| {
4191            let buf = buf.read(cx);
4192            if buf.is_dirty() {
4193                buf.project_path(cx)
4194            } else {
4195                None
4196            }
4197        })
4198    }
4199
4200    fn set_worktrees_from_proto(
4201        &mut self,
4202        worktrees: Vec<proto::WorktreeMetadata>,
4203        cx: &mut Context<Project>,
4204    ) -> Result<()> {
4205        cx.notify();
4206        self.worktree_store.update(cx, |worktree_store, cx| {
4207            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4208        })
4209    }
4210
4211    fn set_collaborators_from_proto(
4212        &mut self,
4213        messages: Vec<proto::Collaborator>,
4214        cx: &mut Context<Self>,
4215    ) -> Result<()> {
4216        let mut collaborators = HashMap::default();
4217        for message in messages {
4218            let collaborator = Collaborator::from_proto(message)?;
4219            collaborators.insert(collaborator.peer_id, collaborator);
4220        }
4221        for old_peer_id in self.collaborators.keys() {
4222            if !collaborators.contains_key(old_peer_id) {
4223                cx.emit(Event::CollaboratorLeft(*old_peer_id));
4224            }
4225        }
4226        self.collaborators = collaborators;
4227        Ok(())
4228    }
4229
4230    pub fn supplementary_language_servers<'a>(
4231        &'a self,
4232        cx: &'a App,
4233    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4234        self.lsp_store.read(cx).supplementary_language_servers()
4235    }
4236
4237    pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4238        self.lsp_store.update(cx, |this, cx| {
4239            this.language_servers_for_local_buffer(buffer, cx)
4240                .any(
4241                    |(_, server)| match server.capabilities().inlay_hint_provider {
4242                        Some(lsp::OneOf::Left(enabled)) => enabled,
4243                        Some(lsp::OneOf::Right(_)) => true,
4244                        None => false,
4245                    },
4246                )
4247        })
4248    }
4249
4250    pub fn language_server_id_for_name(
4251        &self,
4252        buffer: &Buffer,
4253        name: &str,
4254        cx: &mut App,
4255    ) -> Option<LanguageServerId> {
4256        self.lsp_store.update(cx, |this, cx| {
4257            this.language_servers_for_local_buffer(buffer, cx)
4258                .find_map(|(adapter, server)| {
4259                    if adapter.name.0 == name {
4260                        Some(server.server_id())
4261                    } else {
4262                        None
4263                    }
4264                })
4265        })
4266    }
4267
4268    pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
4269        self.lsp_store.update(cx, |this, cx| {
4270            this.language_servers_for_local_buffer(buffer, cx)
4271                .next()
4272                .is_some()
4273        })
4274    }
4275
4276    pub fn buffer_store(&self) -> &Entity<BufferStore> {
4277        &self.buffer_store
4278    }
4279
4280    pub fn git_store(&self) -> &Entity<GitStore> {
4281        &self.git_store
4282    }
4283
4284    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
4285        self.git_store.read(cx).active_repository()
4286    }
4287
4288    pub fn all_repositories(&self, cx: &App) -> Vec<Entity<Repository>> {
4289        self.git_store.read(cx).all_repositories()
4290    }
4291
4292    pub fn repository_and_path_for_buffer_id(
4293        &self,
4294        buffer_id: BufferId,
4295        cx: &App,
4296    ) -> Option<(Entity<Repository>, RepoPath)> {
4297        let path = self
4298            .buffer_for_id(buffer_id, cx)?
4299            .read(cx)
4300            .project_path(cx)?;
4301        self.git_store
4302            .read(cx)
4303            .all_repositories()
4304            .into_iter()
4305            .find_map(|repo| {
4306                Some((
4307                    repo.clone(),
4308                    repo.read(cx).repository_entry.relativize(&path.path).ok()?,
4309                ))
4310            })
4311    }
4312}
4313
4314fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
4315    code_actions
4316        .iter()
4317        .flat_map(|(kind, enabled)| {
4318            if *enabled {
4319                Some(kind.clone().into())
4320            } else {
4321                None
4322            }
4323        })
4324        .collect()
4325}
4326
4327pub struct PathMatchCandidateSet {
4328    pub snapshot: Snapshot,
4329    pub include_ignored: bool,
4330    pub include_root_name: bool,
4331    pub candidates: Candidates,
4332}
4333
4334pub enum Candidates {
4335    /// Only consider directories.
4336    Directories,
4337    /// Only consider files.
4338    Files,
4339    /// Consider directories and files.
4340    Entries,
4341}
4342
4343impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4344    type Candidates = PathMatchCandidateSetIter<'a>;
4345
4346    fn id(&self) -> usize {
4347        self.snapshot.id().to_usize()
4348    }
4349
4350    fn len(&self) -> usize {
4351        match self.candidates {
4352            Candidates::Files => {
4353                if self.include_ignored {
4354                    self.snapshot.file_count()
4355                } else {
4356                    self.snapshot.visible_file_count()
4357                }
4358            }
4359
4360            Candidates::Directories => {
4361                if self.include_ignored {
4362                    self.snapshot.dir_count()
4363                } else {
4364                    self.snapshot.visible_dir_count()
4365                }
4366            }
4367
4368            Candidates::Entries => {
4369                if self.include_ignored {
4370                    self.snapshot.entry_count()
4371                } else {
4372                    self.snapshot.visible_entry_count()
4373                }
4374            }
4375        }
4376    }
4377
4378    fn prefix(&self) -> Arc<str> {
4379        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4380            self.snapshot.root_name().into()
4381        } else if self.include_root_name {
4382            format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4383        } else {
4384            Arc::default()
4385        }
4386    }
4387
4388    fn candidates(&'a self, start: usize) -> Self::Candidates {
4389        PathMatchCandidateSetIter {
4390            traversal: match self.candidates {
4391                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4392                Candidates::Files => self.snapshot.files(self.include_ignored, start),
4393                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4394            },
4395        }
4396    }
4397}
4398
4399pub struct PathMatchCandidateSetIter<'a> {
4400    traversal: Traversal<'a>,
4401}
4402
4403impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4404    type Item = fuzzy::PathMatchCandidate<'a>;
4405
4406    fn next(&mut self) -> Option<Self::Item> {
4407        self.traversal
4408            .next()
4409            .map(|entry| fuzzy::PathMatchCandidate {
4410                is_dir: entry.kind.is_dir(),
4411                path: &entry.path,
4412                char_bag: entry.char_bag,
4413            })
4414    }
4415}
4416
4417impl EventEmitter<Event> for Project {}
4418
4419impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4420    fn from(val: &'a ProjectPath) -> Self {
4421        SettingsLocation {
4422            worktree_id: val.worktree_id,
4423            path: val.path.as_ref(),
4424        }
4425    }
4426}
4427
4428impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4429    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4430        Self {
4431            worktree_id,
4432            path: path.as_ref().into(),
4433        }
4434    }
4435}
4436
4437pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4438    let mut path_components = path.components();
4439    let mut base_components = base.components();
4440    let mut components: Vec<Component> = Vec::new();
4441    loop {
4442        match (path_components.next(), base_components.next()) {
4443            (None, None) => break,
4444            (Some(a), None) => {
4445                components.push(a);
4446                components.extend(path_components.by_ref());
4447                break;
4448            }
4449            (None, _) => components.push(Component::ParentDir),
4450            (Some(a), Some(b)) if components.is_empty() && a == b => (),
4451            (Some(a), Some(Component::CurDir)) => components.push(a),
4452            (Some(a), Some(_)) => {
4453                components.push(Component::ParentDir);
4454                for _ in base_components {
4455                    components.push(Component::ParentDir);
4456                }
4457                components.push(a);
4458                components.extend(path_components.by_ref());
4459                break;
4460            }
4461        }
4462    }
4463    components.iter().map(|c| c.as_os_str()).collect()
4464}
4465
4466fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4467    let mut result = base.to_path_buf();
4468    for component in path.components() {
4469        match component {
4470            Component::ParentDir => {
4471                result.pop();
4472            }
4473            Component::CurDir => (),
4474            _ => result.push(component),
4475        }
4476    }
4477    result
4478}
4479
4480/// ResolvedPath is a path that has been resolved to either a ProjectPath
4481/// or an AbsPath and that *exists*.
4482#[derive(Debug, Clone)]
4483pub enum ResolvedPath {
4484    ProjectPath {
4485        project_path: ProjectPath,
4486        is_dir: bool,
4487    },
4488    AbsPath {
4489        path: PathBuf,
4490        is_dir: bool,
4491    },
4492}
4493
4494impl ResolvedPath {
4495    pub fn abs_path(&self) -> Option<&Path> {
4496        match self {
4497            Self::AbsPath { path, .. } => Some(path.as_path()),
4498            _ => None,
4499        }
4500    }
4501
4502    pub fn project_path(&self) -> Option<&ProjectPath> {
4503        match self {
4504            Self::ProjectPath { project_path, .. } => Some(&project_path),
4505            _ => None,
4506        }
4507    }
4508
4509    pub fn is_file(&self) -> bool {
4510        !self.is_dir()
4511    }
4512
4513    pub fn is_dir(&self) -> bool {
4514        match self {
4515            Self::ProjectPath { is_dir, .. } => *is_dir,
4516            Self::AbsPath { is_dir, .. } => *is_dir,
4517        }
4518    }
4519}
4520
4521impl ProjectItem for Buffer {
4522    fn try_open(
4523        project: &Entity<Project>,
4524        path: &ProjectPath,
4525        cx: &mut App,
4526    ) -> Option<Task<Result<Entity<Self>>>> {
4527        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4528    }
4529
4530    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
4531        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4532    }
4533
4534    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
4535        File::from_dyn(self.file()).map(|file| ProjectPath {
4536            worktree_id: file.worktree_id(cx),
4537            path: file.path().clone(),
4538        })
4539    }
4540
4541    fn is_dirty(&self) -> bool {
4542        self.is_dirty()
4543    }
4544}
4545
4546impl Completion {
4547    /// A key that can be used to sort completions when displaying
4548    /// them to the user.
4549    pub fn sort_key(&self) -> (usize, &str) {
4550        let kind_key = match self.lsp_completion.kind {
4551            Some(lsp::CompletionItemKind::KEYWORD) => 0,
4552            Some(lsp::CompletionItemKind::VARIABLE) => 1,
4553            _ => 2,
4554        };
4555        (kind_key, &self.label.text[self.label.filter_range.clone()])
4556    }
4557
4558    /// Whether this completion is a snippet.
4559    pub fn is_snippet(&self) -> bool {
4560        self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
4561    }
4562
4563    /// Returns the corresponding color for this completion.
4564    ///
4565    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
4566    pub fn color(&self) -> Option<Hsla> {
4567        match self.lsp_completion.kind {
4568            Some(CompletionItemKind::COLOR) => color_extractor::extract_color(&self.lsp_completion),
4569            _ => None,
4570        }
4571    }
4572}
4573
4574pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
4575    entries.sort_by(|entry_a, entry_b| {
4576        let entry_a = entry_a.as_ref();
4577        let entry_b = entry_b.as_ref();
4578        compare_paths(
4579            (&entry_a.path, entry_a.is_file()),
4580            (&entry_b.path, entry_b.is_file()),
4581        )
4582    });
4583}
4584
4585fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
4586    match level {
4587        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
4588        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
4589        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
4590    }
4591}