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