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