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