project.rs

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