project.rs

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