1pub mod agent_registry_store;
2pub mod agent_server_store;
3pub mod buffer_store;
4pub mod color_extractor;
5pub mod connection_manager;
6pub mod context_server_store;
7pub mod debounced_delay;
8pub mod debugger;
9pub mod git_store;
10pub mod image_store;
11pub mod lsp_command;
12pub mod lsp_store;
13pub mod manifest_tree;
14pub mod prettier_store;
15pub mod project_search;
16pub mod project_settings;
17pub mod search;
18pub mod task_inventory;
19pub mod task_store;
20pub mod telemetry_snapshot;
21pub mod terminals;
22pub mod toolchain_store;
23pub mod trusted_worktrees;
24pub mod worktree_store;
25
26mod environment;
27use buffer_diff::BufferDiff;
28use context_server_store::ContextServerStore;
29pub use environment::ProjectEnvironmentEvent;
30use git::repository::get_git_committer;
31use git_store::{Repository, RepositoryId};
32pub mod search_history;
33pub mod yarn;
34
35use dap::inline_value::{InlineValueLocation, VariableLookupKind, VariableScope};
36use itertools::{Either, Itertools};
37
38use crate::{
39 git_store::GitStore,
40 lsp_store::{SymbolLocation, log_store::LogKind},
41 project_search::SearchResultsHandle,
42 trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
43 worktree_store::WorktreeIdCounter,
44};
45pub use agent_registry_store::{AgentRegistryStore, RegistryAgent};
46pub use agent_server_store::{AgentId, AgentServerStore, AgentServersUpdated, ExternalAgentSource};
47pub use git_store::{
48 ConflictRegion, ConflictSet, ConflictSetSnapshot, ConflictSetUpdate,
49 git_traversal::{ChildEntriesGitIter, GitEntry, GitEntryRef, GitTraversal},
50 linked_worktree_short_name, worktrees_directory_for_repo,
51};
52pub use manifest_tree::ManifestTree;
53pub use project_search::{Search, SearchResults};
54pub use worktree_store::WorktreePaths;
55
56use anyhow::{Context as _, Result, anyhow};
57use buffer_store::{BufferStore, BufferStoreEvent};
58use client::{
59 Client, Collaborator, PendingEntitySubscription, ProjectId, TypedEnvelope, UserStore, proto,
60};
61use clock::ReplicaId;
62
63use dap::client::DebugAdapterClient;
64
65use collections::{BTreeSet, HashMap, HashSet, IndexSet};
66use debounced_delay::DebouncedDelay;
67pub use debugger::breakpoint_store::BreakpointWithPosition;
68use debugger::{
69 breakpoint_store::{ActiveStackFrame, BreakpointStore},
70 dap_store::{DapStore, DapStoreEvent},
71 session::Session,
72};
73
74pub use environment::ProjectEnvironment;
75
76use futures::{
77 StreamExt,
78 channel::mpsc::{self, UnboundedReceiver},
79 future::try_join_all,
80};
81pub use image_store::{ImageItem, ImageStore};
82use image_store::{ImageItemEvent, ImageStoreEvent};
83
84use ::git::{blame::Blame, status::FileStatus};
85use gpui::{
86 App, AppContext, AsyncApp, BorrowAppContext, Context, Entity, EventEmitter, Hsla, SharedString,
87 Task, WeakEntity, Window,
88};
89use language::{
90 Buffer, BufferEvent, Capability, CodeLabel, CursorShape, DiskState, Language, LanguageName,
91 LanguageRegistry, PointUtf16, ToOffset, ToPointUtf16, Toolchain, ToolchainMetadata,
92 ToolchainScope, Transaction, Unclipped, language_settings::InlayHintKind,
93 proto::split_operations,
94};
95use lsp::{
96 CodeActionKind, CompletionContext, CompletionItemKind, DocumentHighlightKind, InsertTextMode,
97 LanguageServerBinary, LanguageServerId, LanguageServerName, LanguageServerSelector,
98 MessageActionItem,
99};
100use lsp_command::*;
101use lsp_store::{CompletionDocumentation, LspFormatTarget, OpenLspBufferHandle};
102pub use manifest_tree::ManifestProvidersStore;
103use node_runtime::NodeRuntime;
104use parking_lot::Mutex;
105pub use prettier_store::PrettierStore;
106use project_settings::{ProjectSettings, SettingsObserver, SettingsObserverEvent};
107#[cfg(target_os = "windows")]
108use remote::wsl_path_to_windows_path;
109use remote::{RemoteClient, RemoteConnectionOptions};
110use rpc::{
111 AnyProtoClient, ErrorCode,
112 proto::{LanguageServerPromptResponse, REMOTE_SERVER_PROJECT_ID},
113};
114use search::{SearchInputKind, SearchQuery, SearchResult};
115use search_history::SearchHistory;
116use settings::{InvalidSettingsError, RegisterSetting, Settings, SettingsLocation, SettingsStore};
117use snippet::Snippet;
118pub use snippet_provider;
119use snippet_provider::SnippetProvider;
120use std::{
121 borrow::Cow,
122 collections::BTreeMap,
123 ffi::OsString,
124 future::Future,
125 ops::{Not as _, Range},
126 path::{Path, PathBuf},
127 pin::pin,
128 str::{self, FromStr},
129 sync::Arc,
130 time::Duration,
131};
132
133use task_store::TaskStore;
134use terminals::Terminals;
135use text::{Anchor, BufferId, OffsetRangeExt, Point, Rope};
136use toolchain_store::EmptyToolchainStore;
137use util::{
138 ResultExt as _, maybe,
139 path_list::PathList,
140 paths::{PathStyle, SanitizedPath, is_absolute},
141 rel_path::RelPath,
142};
143use worktree::{CreatedEntry, Snapshot, Traversal};
144pub use worktree::{
145 Entry, EntryKind, FS_WATCH_LATENCY, File, LocalWorktree, PathChange, ProjectEntryId,
146 UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
147 discover_root_repo_common_dir,
148};
149use worktree_store::{WorktreeStore, WorktreeStoreEvent};
150
151pub use fs::*;
152pub use language::Location;
153#[cfg(any(test, feature = "test-support"))]
154pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
155#[cfg(any(test, feature = "test-support"))]
156pub use prettier::RANGE_FORMAT_SUFFIX as TEST_PRETTIER_RANGE_FORMAT_SUFFIX;
157pub use task_inventory::{
158 BasicContextProvider, ContextProviderWithTasks, DebugScenarioContext, Inventory, TaskContexts,
159 TaskSourceKind,
160};
161
162pub use buffer_store::ProjectTransaction;
163pub use lsp_store::{
164 DiagnosticSummary, InvalidationStrategy, LanguageServerLogType, LanguageServerProgress,
165 LanguageServerPromptRequest, LanguageServerStatus, LanguageServerToQuery, LspStore,
166 LspStoreEvent, ProgressToken, SERVER_PROGRESS_THROTTLE_TIMEOUT,
167};
168pub use toolchain_store::{ToolchainStore, Toolchains};
169const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
170
171#[derive(Clone, Copy, Debug)]
172pub struct LocalProjectFlags {
173 pub init_worktree_trust: bool,
174 pub watch_global_configs: bool,
175}
176
177impl Default for LocalProjectFlags {
178 fn default() -> Self {
179 Self {
180 init_worktree_trust: true,
181 watch_global_configs: true,
182 }
183 }
184}
185
186pub trait ProjectItem: 'static {
187 fn try_open(
188 project: &Entity<Project>,
189 path: &ProjectPath,
190 cx: &mut App,
191 ) -> Option<Task<Result<Entity<Self>>>>
192 where
193 Self: Sized;
194 fn entry_id(&self, cx: &App) -> Option<ProjectEntryId>;
195 fn project_path(&self, cx: &App) -> Option<ProjectPath>;
196 fn is_dirty(&self) -> bool;
197}
198
199#[derive(Clone)]
200pub enum OpenedBufferEvent {
201 Disconnected,
202 Ok(BufferId),
203 Err(BufferId, Arc<anyhow::Error>),
204}
205
206/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
207/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
208/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
209///
210/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
211pub struct Project {
212 active_entry: Option<ProjectEntryId>,
213 buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
214 languages: Arc<LanguageRegistry>,
215 dap_store: Entity<DapStore>,
216 agent_server_store: Entity<AgentServerStore>,
217
218 breakpoint_store: Entity<BreakpointStore>,
219 collab_client: Arc<client::Client>,
220 join_project_response_message_id: u32,
221 task_store: Entity<TaskStore>,
222 user_store: Entity<UserStore>,
223 fs: Arc<dyn Fs>,
224 remote_client: Option<Entity<RemoteClient>>,
225 // todo lw explain the client_state x remote_client matrix, its super confusing
226 client_state: ProjectClientState,
227 git_store: Entity<GitStore>,
228 collaborators: HashMap<proto::PeerId, Collaborator>,
229 client_subscriptions: Vec<client::Subscription>,
230 worktree_store: Entity<WorktreeStore>,
231 buffer_store: Entity<BufferStore>,
232 context_server_store: Entity<ContextServerStore>,
233 image_store: Entity<ImageStore>,
234 lsp_store: Entity<LspStore>,
235 _subscriptions: Vec<gpui::Subscription>,
236 buffers_needing_diff: HashSet<WeakEntity<Buffer>>,
237 git_diff_debouncer: DebouncedDelay<Self>,
238 remotely_created_models: Arc<Mutex<RemotelyCreatedModels>>,
239 terminals: Terminals,
240 node: Option<NodeRuntime>,
241 search_history: SearchHistory,
242 search_included_history: SearchHistory,
243 search_excluded_history: SearchHistory,
244 snippets: Entity<SnippetProvider>,
245 environment: Entity<ProjectEnvironment>,
246 settings_observer: Entity<SettingsObserver>,
247 toolchain_store: Option<Entity<ToolchainStore>>,
248 agent_location: Option<AgentLocation>,
249 downloading_files: Arc<Mutex<HashMap<(WorktreeId, String), DownloadingFile>>>,
250 last_worktree_paths: WorktreePaths,
251}
252
253struct DownloadingFile {
254 destination_path: PathBuf,
255 chunks: Vec<u8>,
256 total_size: u64,
257 file_id: Option<u64>, // Set when we receive the State message
258}
259
260#[derive(Clone, Debug, PartialEq, Eq)]
261pub struct AgentLocation {
262 pub buffer: WeakEntity<Buffer>,
263 pub position: Anchor,
264}
265
266#[derive(Default)]
267struct RemotelyCreatedModels {
268 worktrees: Vec<Entity<Worktree>>,
269 buffers: Vec<Entity<Buffer>>,
270 retain_count: usize,
271}
272
273struct RemotelyCreatedModelGuard {
274 remote_models: std::sync::Weak<Mutex<RemotelyCreatedModels>>,
275}
276
277impl Drop for RemotelyCreatedModelGuard {
278 fn drop(&mut self) {
279 if let Some(remote_models) = self.remote_models.upgrade() {
280 let mut remote_models = remote_models.lock();
281 assert!(
282 remote_models.retain_count > 0,
283 "RemotelyCreatedModelGuard dropped too many times"
284 );
285 remote_models.retain_count -= 1;
286 if remote_models.retain_count == 0 {
287 remote_models.buffers.clear();
288 remote_models.worktrees.clear();
289 }
290 }
291 }
292}
293/// Message ordered with respect to buffer operations
294#[derive(Debug)]
295enum BufferOrderedMessage {
296 Operation {
297 buffer_id: BufferId,
298 operation: proto::Operation,
299 },
300 LanguageServerUpdate {
301 language_server_id: LanguageServerId,
302 message: proto::update_language_server::Variant,
303 name: Option<LanguageServerName>,
304 },
305 Resync,
306}
307
308#[derive(Debug)]
309enum ProjectClientState {
310 /// Single-player mode.
311 Local,
312 /// Multi-player mode but still a local project.
313 Shared { remote_id: u64 },
314 /// Multi-player mode but working on a remote project.
315 Collab {
316 sharing_has_stopped: bool,
317 capability: Capability,
318 remote_id: u64,
319 replica_id: ReplicaId,
320 },
321}
322
323/// A link to display in a toast notification, useful to point to documentation.
324#[derive(PartialEq, Debug, Clone)]
325pub struct ToastLink {
326 pub label: &'static str,
327 pub url: &'static str,
328}
329
330#[derive(Clone, Debug, PartialEq)]
331pub enum Event {
332 LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
333 LanguageServerRemoved(LanguageServerId),
334 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
335 // [`lsp::notification::DidOpenTextDocument`] was sent to this server using the buffer data.
336 // Zed's buffer-related data is updated accordingly.
337 LanguageServerBufferRegistered {
338 server_id: LanguageServerId,
339 buffer_id: BufferId,
340 buffer_abs_path: PathBuf,
341 name: Option<LanguageServerName>,
342 },
343 ToggleLspLogs {
344 server_id: LanguageServerId,
345 enabled: bool,
346 toggled_log_kind: LogKind,
347 },
348 Toast {
349 notification_id: SharedString,
350 message: String,
351 /// Optional link to display as a button in the toast.
352 link: Option<ToastLink>,
353 },
354 HideToast {
355 notification_id: SharedString,
356 },
357 LanguageServerPrompt(LanguageServerPromptRequest),
358 LanguageNotFound(Entity<Buffer>),
359 ActiveEntryChanged(Option<ProjectEntryId>),
360 ActivateProjectPanel,
361 WorktreeAdded(WorktreeId),
362 WorktreeOrderChanged,
363 WorktreeRemoved(WorktreeId),
364 WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
365 WorktreeUpdatedRootRepoCommonDir(WorktreeId),
366 WorktreePathsChanged {
367 old_worktree_paths: WorktreePaths,
368 },
369 DiskBasedDiagnosticsStarted {
370 language_server_id: LanguageServerId,
371 },
372 DiskBasedDiagnosticsFinished {
373 language_server_id: LanguageServerId,
374 },
375 DiagnosticsUpdated {
376 paths: Vec<ProjectPath>,
377 language_server_id: LanguageServerId,
378 },
379 RemoteIdChanged(Option<u64>),
380 DisconnectedFromHost,
381 DisconnectedFromRemote {
382 server_not_running: bool,
383 },
384 Closed,
385 DeletedEntry(WorktreeId, ProjectEntryId),
386 CollaboratorUpdated {
387 old_peer_id: proto::PeerId,
388 new_peer_id: proto::PeerId,
389 },
390 CollaboratorJoined(proto::PeerId),
391 CollaboratorLeft(proto::PeerId),
392 HostReshared,
393 Reshared,
394 Rejoined,
395 RefreshInlayHints {
396 server_id: LanguageServerId,
397 request_id: Option<usize>,
398 },
399 RefreshSemanticTokens {
400 server_id: LanguageServerId,
401 request_id: Option<usize>,
402 },
403 RefreshCodeLens,
404 RevealInProjectPanel(ProjectEntryId),
405 SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
406 ExpandedAllForEntry(WorktreeId, ProjectEntryId),
407 EntryRenamed(ProjectTransaction, ProjectPath, PathBuf),
408 WorkspaceEditApplied(ProjectTransaction),
409 AgentLocationChanged,
410 BufferEdited,
411}
412
413pub struct AgentLocationChanged;
414
415pub enum DebugAdapterClientState {
416 Starting(Task<Option<Arc<DebugAdapterClient>>>),
417 Running(Arc<DebugAdapterClient>),
418}
419
420#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
421pub struct ProjectPath {
422 pub worktree_id: WorktreeId,
423 pub path: Arc<RelPath>,
424}
425
426impl ProjectPath {
427 pub fn from_file(value: &dyn language::File, cx: &App) -> Self {
428 ProjectPath {
429 worktree_id: value.worktree_id(cx),
430 path: value.path().clone(),
431 }
432 }
433
434 pub fn from_proto(p: proto::ProjectPath) -> Option<Self> {
435 Some(Self {
436 worktree_id: WorktreeId::from_proto(p.worktree_id),
437 path: RelPath::from_proto(&p.path).log_err()?,
438 })
439 }
440
441 pub fn to_proto(&self) -> proto::ProjectPath {
442 proto::ProjectPath {
443 worktree_id: self.worktree_id.to_proto(),
444 path: self.path.as_ref().to_proto(),
445 }
446 }
447
448 pub fn root_path(worktree_id: WorktreeId) -> Self {
449 Self {
450 worktree_id,
451 path: RelPath::empty().into(),
452 }
453 }
454
455 pub fn starts_with(&self, other: &ProjectPath) -> bool {
456 self.worktree_id == other.worktree_id && self.path.starts_with(&other.path)
457 }
458}
459
460#[derive(Debug, Default)]
461pub enum PrepareRenameResponse {
462 Success(Range<Anchor>),
463 OnlyUnpreparedRenameSupported,
464 #[default]
465 InvalidPosition,
466}
467
468#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
469pub enum InlayId {
470 EditPrediction(usize),
471 DebuggerValue(usize),
472 // LSP
473 Hint(usize),
474 Color(usize),
475 ReplResult(usize),
476}
477
478impl InlayId {
479 pub fn id(&self) -> usize {
480 match self {
481 Self::EditPrediction(id) => *id,
482 Self::DebuggerValue(id) => *id,
483 Self::Hint(id) => *id,
484 Self::Color(id) => *id,
485 Self::ReplResult(id) => *id,
486 }
487 }
488}
489
490#[derive(Debug, Clone, PartialEq, Eq)]
491pub struct InlayHint {
492 pub position: language::Anchor,
493 pub label: InlayHintLabel,
494 pub kind: Option<InlayHintKind>,
495 pub padding_left: bool,
496 pub padding_right: bool,
497 pub tooltip: Option<InlayHintTooltip>,
498 pub resolve_state: ResolveState,
499}
500
501/// The user's intent behind a given completion confirmation.
502#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
503pub enum CompletionIntent {
504 /// The user intends to 'commit' this result, if possible.
505 /// Completion confirmations should run side effects.
506 ///
507 /// For LSP completions, will respect the setting `completions.lsp_insert_mode`.
508 Complete,
509 /// Similar to [Self::Complete], but behaves like `lsp_insert_mode` is set to `insert`.
510 CompleteWithInsert,
511 /// Similar to [Self::Complete], but behaves like `lsp_insert_mode` is set to `replace`.
512 CompleteWithReplace,
513 /// The user intends to continue 'composing' this completion.
514 /// Completion confirmations should not run side effects and
515 /// let the user continue composing their action.
516 Compose,
517}
518
519impl CompletionIntent {
520 pub fn is_complete(&self) -> bool {
521 self == &Self::Complete
522 }
523
524 pub fn is_compose(&self) -> bool {
525 self == &Self::Compose
526 }
527}
528
529/// Similar to `CoreCompletion`, but with extra metadata attached.
530#[derive(Clone)]
531pub struct Completion {
532 /// The range of text that will be replaced by this completion.
533 pub replace_range: Range<Anchor>,
534 /// The new text that will be inserted.
535 pub new_text: String,
536 /// A label for this completion that is shown in the menu.
537 pub label: CodeLabel,
538 /// The documentation for this completion.
539 pub documentation: Option<CompletionDocumentation>,
540 /// Completion data source which it was constructed from.
541 pub source: CompletionSource,
542 /// A path to an icon for this completion that is shown in the menu.
543 pub icon_path: Option<SharedString>,
544 /// Text starting here and ending at the cursor will be used as the query for filtering this completion.
545 ///
546 /// If None, the start of the surrounding word is used.
547 pub match_start: Option<text::Anchor>,
548 /// Key used for de-duplicating snippets. If None, always considered unique.
549 pub snippet_deduplication_key: Option<(usize, usize)>,
550 /// Whether to adjust indentation (the default) or not.
551 pub insert_text_mode: Option<InsertTextMode>,
552 /// An optional callback to invoke when this completion is confirmed.
553 /// Returns whether new completions should be retriggered after the current one.
554 /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
555 /// if no confirmation is provided or `false` is returned, the completion will be committed.
556 pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut Window, &mut App) -> bool>>,
557}
558
559#[derive(Debug, Clone)]
560pub enum CompletionSource {
561 Lsp {
562 /// The alternate `insert` range, if provided by the LSP server.
563 insert_range: Option<Range<Anchor>>,
564 /// The id of the language server that produced this completion.
565 server_id: LanguageServerId,
566 /// The raw completion provided by the language server.
567 lsp_completion: Box<lsp::CompletionItem>,
568 /// A set of defaults for this completion item.
569 lsp_defaults: Option<Arc<lsp::CompletionListItemDefaults>>,
570 /// Whether this completion has been resolved, to ensure it happens once per completion.
571 resolved: bool,
572 },
573 Dap {
574 /// The sort text for this completion.
575 sort_text: String,
576 },
577 Custom,
578 BufferWord {
579 word_range: Range<Anchor>,
580 resolved: bool,
581 },
582}
583
584impl CompletionSource {
585 pub fn server_id(&self) -> Option<LanguageServerId> {
586 if let CompletionSource::Lsp { server_id, .. } = self {
587 Some(*server_id)
588 } else {
589 None
590 }
591 }
592
593 pub fn lsp_completion(&self, apply_defaults: bool) -> Option<Cow<'_, lsp::CompletionItem>> {
594 if let Self::Lsp {
595 lsp_completion,
596 lsp_defaults,
597 ..
598 } = self
599 {
600 if apply_defaults && let Some(lsp_defaults) = lsp_defaults {
601 let mut completion_with_defaults = *lsp_completion.clone();
602 let default_commit_characters = lsp_defaults.commit_characters.as_ref();
603 let default_edit_range = lsp_defaults.edit_range.as_ref();
604 let default_insert_text_format = lsp_defaults.insert_text_format.as_ref();
605 let default_insert_text_mode = lsp_defaults.insert_text_mode.as_ref();
606
607 if default_commit_characters.is_some()
608 || default_edit_range.is_some()
609 || default_insert_text_format.is_some()
610 || default_insert_text_mode.is_some()
611 {
612 if completion_with_defaults.commit_characters.is_none()
613 && default_commit_characters.is_some()
614 {
615 completion_with_defaults.commit_characters =
616 default_commit_characters.cloned()
617 }
618 if completion_with_defaults.text_edit.is_none() {
619 match default_edit_range {
620 Some(lsp::CompletionListItemDefaultsEditRange::Range(range)) => {
621 completion_with_defaults.text_edit =
622 Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
623 range: *range,
624 new_text: completion_with_defaults.label.clone(),
625 }))
626 }
627 Some(lsp::CompletionListItemDefaultsEditRange::InsertAndReplace {
628 insert,
629 replace,
630 }) => {
631 completion_with_defaults.text_edit =
632 Some(lsp::CompletionTextEdit::InsertAndReplace(
633 lsp::InsertReplaceEdit {
634 new_text: completion_with_defaults.label.clone(),
635 insert: *insert,
636 replace: *replace,
637 },
638 ))
639 }
640 None => {}
641 }
642 }
643 if completion_with_defaults.insert_text_format.is_none()
644 && default_insert_text_format.is_some()
645 {
646 completion_with_defaults.insert_text_format =
647 default_insert_text_format.cloned()
648 }
649 if completion_with_defaults.insert_text_mode.is_none()
650 && default_insert_text_mode.is_some()
651 {
652 completion_with_defaults.insert_text_mode =
653 default_insert_text_mode.cloned()
654 }
655 }
656 return Some(Cow::Owned(completion_with_defaults));
657 }
658 Some(Cow::Borrowed(lsp_completion))
659 } else {
660 None
661 }
662 }
663}
664
665impl std::fmt::Debug for Completion {
666 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
667 f.debug_struct("Completion")
668 .field("replace_range", &self.replace_range)
669 .field("new_text", &self.new_text)
670 .field("label", &self.label)
671 .field("documentation", &self.documentation)
672 .field("source", &self.source)
673 .finish()
674 }
675}
676
677/// Response from a source of completions.
678pub struct CompletionResponse {
679 pub completions: Vec<Completion>,
680 pub display_options: CompletionDisplayOptions,
681 /// When false, indicates that the list is complete and does not need to be re-queried if it
682 /// can be filtered instead.
683 pub is_incomplete: bool,
684}
685
686#[derive(Default)]
687pub struct CompletionDisplayOptions {
688 pub dynamic_width: bool,
689}
690
691impl CompletionDisplayOptions {
692 pub fn merge(&mut self, other: &CompletionDisplayOptions) {
693 self.dynamic_width = self.dynamic_width && other.dynamic_width;
694 }
695}
696
697/// Response from language server completion request.
698#[derive(Clone, Debug, Default)]
699pub(crate) struct CoreCompletionResponse {
700 pub completions: Vec<CoreCompletion>,
701 /// When false, indicates that the list is complete and does not need to be re-queried if it
702 /// can be filtered instead.
703 pub is_incomplete: bool,
704}
705
706/// A generic completion that can come from different sources.
707#[derive(Clone, Debug)]
708pub(crate) struct CoreCompletion {
709 replace_range: Range<Anchor>,
710 new_text: String,
711 source: CompletionSource,
712}
713
714/// A code action provided by a language server.
715#[derive(Clone, Debug, PartialEq)]
716pub struct CodeAction {
717 /// The id of the language server that produced this code action.
718 pub server_id: LanguageServerId,
719 /// The range of the buffer where this code action is applicable.
720 pub range: Range<Anchor>,
721 /// The raw code action provided by the language server.
722 /// Can be either an action or a command.
723 pub lsp_action: LspAction,
724 /// Whether the action needs to be resolved using the language server.
725 pub resolved: bool,
726}
727
728/// An action sent back by a language server.
729#[derive(Clone, Debug, PartialEq)]
730pub enum LspAction {
731 /// An action with the full data, may have a command or may not.
732 /// May require resolving.
733 Action(Box<lsp::CodeAction>),
734 /// A command data to run as an action.
735 Command(lsp::Command),
736 /// A code lens data to run as an action.
737 CodeLens(lsp::CodeLens),
738}
739
740impl LspAction {
741 pub fn title(&self) -> &str {
742 match self {
743 Self::Action(action) => &action.title,
744 Self::Command(command) => &command.title,
745 Self::CodeLens(lens) => lens
746 .command
747 .as_ref()
748 .map(|command| command.title.as_str())
749 .unwrap_or("Unknown command"),
750 }
751 }
752
753 pub fn action_kind(&self) -> Option<lsp::CodeActionKind> {
754 match self {
755 Self::Action(action) => action.kind.clone(),
756 Self::Command(_) => Some(lsp::CodeActionKind::new("command")),
757 Self::CodeLens(_) => Some(lsp::CodeActionKind::new("code lens")),
758 }
759 }
760
761 pub fn edit(&self) -> Option<&lsp::WorkspaceEdit> {
762 match self {
763 Self::Action(action) => action.edit.as_ref(),
764 Self::Command(_) => None,
765 Self::CodeLens(_) => None,
766 }
767 }
768
769 pub fn command(&self) -> Option<&lsp::Command> {
770 match self {
771 Self::Action(action) => action.command.as_ref(),
772 Self::Command(command) => Some(command),
773 Self::CodeLens(lens) => lens.command.as_ref(),
774 }
775 }
776}
777
778#[derive(Debug, Clone, PartialEq, Eq)]
779pub enum ResolveState {
780 Resolved,
781 CanResolve(LanguageServerId, Option<lsp::LSPAny>),
782 Resolving,
783}
784impl InlayHint {
785 pub fn text(&self) -> Rope {
786 match &self.label {
787 InlayHintLabel::String(s) => Rope::from(s),
788 InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &*part.value).collect(),
789 }
790 }
791}
792
793#[derive(Debug, Clone, PartialEq, Eq)]
794pub enum InlayHintLabel {
795 String(String),
796 LabelParts(Vec<InlayHintLabelPart>),
797}
798
799#[derive(Debug, Clone, PartialEq, Eq)]
800pub struct InlayHintLabelPart {
801 pub value: String,
802 pub tooltip: Option<InlayHintLabelPartTooltip>,
803 pub location: Option<(LanguageServerId, lsp::Location)>,
804}
805
806#[derive(Debug, Clone, PartialEq, Eq)]
807pub enum InlayHintTooltip {
808 String(String),
809 MarkupContent(MarkupContent),
810}
811
812#[derive(Debug, Clone, PartialEq, Eq)]
813pub enum InlayHintLabelPartTooltip {
814 String(String),
815 MarkupContent(MarkupContent),
816}
817
818#[derive(Debug, Clone, PartialEq, Eq)]
819pub struct MarkupContent {
820 pub kind: HoverBlockKind,
821 pub value: String,
822}
823
824#[derive(Debug, Clone, PartialEq)]
825pub struct LocationLink {
826 pub origin: Option<Location>,
827 pub target: Location,
828}
829
830#[derive(Debug)]
831pub struct DocumentHighlight {
832 pub range: Range<language::Anchor>,
833 pub kind: DocumentHighlightKind,
834}
835
836#[derive(Clone, Debug)]
837pub struct Symbol {
838 pub language_server_name: LanguageServerName,
839 pub source_worktree_id: WorktreeId,
840 pub source_language_server_id: LanguageServerId,
841 pub path: SymbolLocation,
842 pub label: CodeLabel,
843 pub name: String,
844 pub kind: lsp::SymbolKind,
845 pub range: Range<Unclipped<PointUtf16>>,
846 pub container_name: Option<String>,
847}
848
849#[derive(Clone, Debug)]
850pub struct DocumentSymbol {
851 pub name: String,
852 pub kind: lsp::SymbolKind,
853 pub range: Range<Unclipped<PointUtf16>>,
854 pub selection_range: Range<Unclipped<PointUtf16>>,
855 pub children: Vec<DocumentSymbol>,
856}
857
858#[derive(Clone, Debug, PartialEq)]
859pub struct HoverBlock {
860 pub text: String,
861 pub kind: HoverBlockKind,
862}
863
864#[derive(Clone, Debug, PartialEq, Eq)]
865pub enum HoverBlockKind {
866 PlainText,
867 Markdown,
868 Code { language: String },
869}
870
871#[derive(Debug, Clone)]
872pub struct Hover {
873 pub contents: Vec<HoverBlock>,
874 pub range: Option<Range<language::Anchor>>,
875 pub language: Option<Arc<Language>>,
876}
877
878impl Hover {
879 pub fn is_empty(&self) -> bool {
880 self.contents.iter().all(|block| block.text.is_empty())
881 }
882}
883
884enum EntitySubscription {
885 Project(PendingEntitySubscription<Project>),
886 BufferStore(PendingEntitySubscription<BufferStore>),
887 GitStore(PendingEntitySubscription<GitStore>),
888 WorktreeStore(PendingEntitySubscription<WorktreeStore>),
889 LspStore(PendingEntitySubscription<LspStore>),
890 SettingsObserver(PendingEntitySubscription<SettingsObserver>),
891 DapStore(PendingEntitySubscription<DapStore>),
892 BreakpointStore(PendingEntitySubscription<BreakpointStore>),
893}
894
895#[derive(Debug, Clone)]
896pub struct DirectoryItem {
897 pub path: PathBuf,
898 pub is_dir: bool,
899}
900
901#[derive(Clone, Debug, PartialEq)]
902pub struct DocumentColor {
903 pub lsp_range: lsp::Range,
904 pub color: lsp::Color,
905 pub resolved: bool,
906 pub color_presentations: Vec<ColorPresentation>,
907}
908
909impl Eq for DocumentColor {}
910
911impl std::hash::Hash for DocumentColor {
912 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
913 self.lsp_range.hash(state);
914 self.color.red.to_bits().hash(state);
915 self.color.green.to_bits().hash(state);
916 self.color.blue.to_bits().hash(state);
917 self.color.alpha.to_bits().hash(state);
918 self.resolved.hash(state);
919 self.color_presentations.hash(state);
920 }
921}
922
923#[derive(Clone, Debug, PartialEq, Eq)]
924pub struct ColorPresentation {
925 pub label: SharedString,
926 pub text_edit: Option<lsp::TextEdit>,
927 pub additional_text_edits: Vec<lsp::TextEdit>,
928}
929
930impl std::hash::Hash for ColorPresentation {
931 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
932 self.label.hash(state);
933 if let Some(ref edit) = self.text_edit {
934 edit.range.hash(state);
935 edit.new_text.hash(state);
936 }
937 self.additional_text_edits.len().hash(state);
938 for edit in &self.additional_text_edits {
939 edit.range.hash(state);
940 edit.new_text.hash(state);
941 }
942 }
943}
944
945#[derive(Clone)]
946pub enum DirectoryLister {
947 Project(Entity<Project>),
948 Local(Entity<Project>, Arc<dyn Fs>),
949}
950
951impl std::fmt::Debug for DirectoryLister {
952 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
953 match self {
954 DirectoryLister::Project(project) => {
955 write!(f, "DirectoryLister::Project({project:?})")
956 }
957 DirectoryLister::Local(project, _) => {
958 write!(f, "DirectoryLister::Local({project:?})")
959 }
960 }
961 }
962}
963
964impl DirectoryLister {
965 pub fn is_local(&self, cx: &App) -> bool {
966 match self {
967 DirectoryLister::Local(..) => true,
968 DirectoryLister::Project(project) => project.read(cx).is_local(),
969 }
970 }
971
972 pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &App) -> Cow<'a, str> {
973 if self.is_local(cx) {
974 shellexpand::tilde(path)
975 } else {
976 Cow::from(path)
977 }
978 }
979
980 pub fn default_query(&self, cx: &mut App) -> String {
981 let project = match self {
982 DirectoryLister::Project(project) => project,
983 DirectoryLister::Local(project, _) => project,
984 }
985 .read(cx);
986 let path_style = project.path_style(cx);
987 project
988 .visible_worktrees(cx)
989 .next()
990 .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().into_owned())
991 .or_else(|| std::env::home_dir().map(|dir| dir.to_string_lossy().into_owned()))
992 .map(|mut s| {
993 s.push_str(path_style.primary_separator());
994 s
995 })
996 .unwrap_or_else(|| {
997 if path_style.is_windows() {
998 "C:\\"
999 } else {
1000 "~/"
1001 }
1002 .to_string()
1003 })
1004 }
1005
1006 pub fn list_directory(&self, path: String, cx: &mut App) -> Task<Result<Vec<DirectoryItem>>> {
1007 match self {
1008 DirectoryLister::Project(project) => {
1009 project.update(cx, |project, cx| project.list_directory(path, cx))
1010 }
1011 DirectoryLister::Local(_, fs) => {
1012 let fs = fs.clone();
1013 cx.background_spawn(async move {
1014 let mut results = vec![];
1015 let expanded = shellexpand::tilde(&path);
1016 let query = Path::new(expanded.as_ref());
1017 let mut response = fs.read_dir(query).await?;
1018 while let Some(path) = response.next().await {
1019 let path = path?;
1020 if let Some(file_name) = path.file_name() {
1021 results.push(DirectoryItem {
1022 path: PathBuf::from(file_name.to_os_string()),
1023 is_dir: fs.is_dir(&path).await,
1024 });
1025 }
1026 }
1027 Ok(results)
1028 })
1029 }
1030 }
1031 }
1032
1033 pub fn path_style(&self, cx: &App) -> PathStyle {
1034 match self {
1035 Self::Local(project, ..) | Self::Project(project, ..) => {
1036 project.read(cx).path_style(cx)
1037 }
1038 }
1039 }
1040}
1041
1042pub const CURRENT_PROJECT_FEATURES: &[&str] = &["new-style-anchors"];
1043
1044#[cfg(feature = "test-support")]
1045pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
1046 trigger_kind: lsp::CompletionTriggerKind::INVOKED,
1047 trigger_character: None,
1048};
1049
1050/// An LSP diagnostics associated with a certain language server.
1051#[derive(Clone, Debug, Default)]
1052pub enum LspPullDiagnostics {
1053 #[default]
1054 Default,
1055 Response {
1056 /// The id of the language server that produced diagnostics.
1057 server_id: LanguageServerId,
1058 /// URI of the resource,
1059 uri: lsp::Uri,
1060 /// The ID provided by the dynamic registration that produced diagnostics.
1061 registration_id: Option<SharedString>,
1062 /// The diagnostics produced by this language server.
1063 diagnostics: PulledDiagnostics,
1064 },
1065}
1066
1067#[derive(Clone, Debug)]
1068pub enum PulledDiagnostics {
1069 Unchanged {
1070 /// An ID the current pulled batch for this file.
1071 /// If given, can be used to query workspace diagnostics partially.
1072 result_id: SharedString,
1073 },
1074 Changed {
1075 result_id: Option<SharedString>,
1076 diagnostics: Vec<lsp::Diagnostic>,
1077 },
1078}
1079
1080/// Whether to disable all AI features in Zed.
1081///
1082/// Default: false
1083#[derive(Copy, Clone, Debug, RegisterSetting)]
1084pub struct DisableAiSettings {
1085 pub disable_ai: bool,
1086}
1087
1088impl settings::Settings for DisableAiSettings {
1089 fn from_settings(content: &settings::SettingsContent) -> Self {
1090 Self {
1091 disable_ai: content.project.disable_ai.unwrap().0,
1092 }
1093 }
1094}
1095
1096impl DisableAiSettings {
1097 /// Returns whether AI is disabled for the given file.
1098 ///
1099 /// This checks the project-level settings for the file's worktree,
1100 /// allowing `disable_ai` to be configured per-project in `.zed/settings.json`.
1101 pub fn is_ai_disabled_for_buffer(buffer: Option<&Entity<Buffer>>, cx: &App) -> bool {
1102 Self::is_ai_disabled_for_file(buffer.and_then(|buffer| buffer.read(cx).file()), cx)
1103 }
1104
1105 pub fn is_ai_disabled_for_file(file: Option<&Arc<dyn language::File>>, cx: &App) -> bool {
1106 let location = file.map(|f| settings::SettingsLocation {
1107 worktree_id: f.worktree_id(cx),
1108 path: f.path().as_ref(),
1109 });
1110 Self::get(location, cx).disable_ai
1111 }
1112}
1113
1114impl Project {
1115 pub fn init(client: &Arc<Client>, cx: &mut App) {
1116 connection_manager::init(client.clone(), cx);
1117
1118 let client: AnyProtoClient = client.clone().into();
1119 client.add_entity_message_handler(Self::handle_add_collaborator);
1120 client.add_entity_message_handler(Self::handle_update_project_collaborator);
1121 client.add_entity_message_handler(Self::handle_remove_collaborator);
1122 client.add_entity_message_handler(Self::handle_update_project);
1123 client.add_entity_message_handler(Self::handle_unshare_project);
1124 client.add_entity_request_handler(Self::handle_update_buffer);
1125 client.add_entity_message_handler(Self::handle_update_worktree);
1126 client.add_entity_request_handler(Self::handle_synchronize_buffers);
1127
1128 client.add_entity_request_handler(Self::handle_search_candidate_buffers);
1129 client.add_entity_request_handler(Self::handle_open_buffer_by_id);
1130 client.add_entity_request_handler(Self::handle_open_buffer_by_path);
1131 client.add_entity_request_handler(Self::handle_open_new_buffer);
1132 client.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1133 client.add_entity_message_handler(Self::handle_toggle_lsp_logs);
1134 client.add_entity_message_handler(Self::handle_create_image_for_peer);
1135 client.add_entity_request_handler(Self::handle_find_search_candidates_chunk);
1136 client.add_entity_message_handler(Self::handle_find_search_candidates_cancel);
1137 client.add_entity_message_handler(Self::handle_create_file_for_peer);
1138
1139 WorktreeStore::init(&client);
1140 BufferStore::init(&client);
1141 LspStore::init(&client);
1142 GitStore::init(&client);
1143 SettingsObserver::init(&client);
1144 TaskStore::init(Some(&client));
1145 ToolchainStore::init(&client);
1146 DapStore::init(&client, cx);
1147 BreakpointStore::init(&client);
1148 context_server_store::init(cx);
1149 }
1150
1151 pub fn local(
1152 client: Arc<Client>,
1153 node: NodeRuntime,
1154 user_store: Entity<UserStore>,
1155 languages: Arc<LanguageRegistry>,
1156 fs: Arc<dyn Fs>,
1157 env: Option<HashMap<String, String>>,
1158 flags: LocalProjectFlags,
1159 cx: &mut App,
1160 ) -> Entity<Self> {
1161 cx.new(|cx: &mut Context<Self>| {
1162 let (tx, rx) = mpsc::unbounded();
1163 cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1164 .detach();
1165 let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1166 let worktree_store =
1167 cx.new(|cx| WorktreeStore::local(false, fs.clone(), WorktreeIdCounter::get(cx)));
1168 if flags.init_worktree_trust {
1169 trusted_worktrees::track_worktree_trust(
1170 worktree_store.clone(),
1171 None,
1172 None,
1173 None,
1174 cx,
1175 );
1176 }
1177 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1178 .detach();
1179
1180 let weak_self = cx.weak_entity();
1181 let context_server_store = cx.new(|cx| {
1182 ContextServerStore::local(
1183 worktree_store.clone(),
1184 Some(weak_self.clone()),
1185 false,
1186 cx,
1187 )
1188 });
1189
1190 let environment = cx.new(|cx| {
1191 ProjectEnvironment::new(env, worktree_store.downgrade(), None, false, cx)
1192 });
1193 let manifest_tree = ManifestTree::new(worktree_store.clone(), cx);
1194 let toolchain_store = cx.new(|cx| {
1195 ToolchainStore::local(
1196 languages.clone(),
1197 worktree_store.clone(),
1198 environment.clone(),
1199 manifest_tree.clone(),
1200 cx,
1201 )
1202 });
1203
1204 let buffer_store = cx.new(|cx| BufferStore::local(worktree_store.clone(), cx));
1205 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1206 .detach();
1207
1208 let breakpoint_store =
1209 cx.new(|_| BreakpointStore::local(worktree_store.clone(), buffer_store.clone()));
1210
1211 let dap_store = cx.new(|cx| {
1212 DapStore::new_local(
1213 client.http_client(),
1214 node.clone(),
1215 fs.clone(),
1216 environment.clone(),
1217 toolchain_store.read(cx).as_language_toolchain_store(),
1218 worktree_store.clone(),
1219 breakpoint_store.clone(),
1220 false,
1221 cx,
1222 )
1223 });
1224 cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1225
1226 let image_store = cx.new(|cx| ImageStore::local(worktree_store.clone(), cx));
1227 cx.subscribe(&image_store, Self::on_image_store_event)
1228 .detach();
1229
1230 let prettier_store = cx.new(|cx| {
1231 PrettierStore::new(
1232 node.clone(),
1233 fs.clone(),
1234 languages.clone(),
1235 worktree_store.clone(),
1236 cx,
1237 )
1238 });
1239
1240 let git_store = cx.new(|cx| {
1241 GitStore::local(
1242 &worktree_store,
1243 buffer_store.clone(),
1244 environment.clone(),
1245 fs.clone(),
1246 cx,
1247 )
1248 });
1249
1250 let task_store = cx.new(|cx| {
1251 TaskStore::local(
1252 buffer_store.downgrade(),
1253 worktree_store.clone(),
1254 toolchain_store.read(cx).as_language_toolchain_store(),
1255 environment.clone(),
1256 git_store.clone(),
1257 cx,
1258 )
1259 });
1260
1261 let settings_observer = cx.new(|cx| {
1262 SettingsObserver::new_local(
1263 fs.clone(),
1264 worktree_store.clone(),
1265 task_store.clone(),
1266 flags.watch_global_configs,
1267 cx,
1268 )
1269 });
1270 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1271 .detach();
1272
1273 let lsp_store = cx.new(|cx| {
1274 LspStore::new_local(
1275 buffer_store.clone(),
1276 worktree_store.clone(),
1277 prettier_store.clone(),
1278 toolchain_store
1279 .read(cx)
1280 .as_local_store()
1281 .expect("Toolchain store to be local")
1282 .clone(),
1283 environment.clone(),
1284 manifest_tree,
1285 languages.clone(),
1286 client.http_client(),
1287 fs.clone(),
1288 cx,
1289 )
1290 });
1291
1292 let agent_server_store = cx.new(|cx| {
1293 AgentServerStore::local(
1294 node.clone(),
1295 fs.clone(),
1296 environment.clone(),
1297 client.http_client(),
1298 cx,
1299 )
1300 });
1301
1302 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1303
1304 Self {
1305 buffer_ordered_messages_tx: tx,
1306 collaborators: Default::default(),
1307 worktree_store,
1308 buffer_store,
1309 image_store,
1310 lsp_store,
1311 context_server_store,
1312 join_project_response_message_id: 0,
1313 client_state: ProjectClientState::Local,
1314 git_store,
1315 client_subscriptions: Vec::new(),
1316 _subscriptions: vec![cx.on_release(Self::release)],
1317 active_entry: None,
1318 snippets,
1319 languages,
1320 collab_client: client,
1321 task_store,
1322 user_store,
1323 settings_observer,
1324 fs,
1325 remote_client: None,
1326 breakpoint_store,
1327 dap_store,
1328 agent_server_store,
1329
1330 buffers_needing_diff: Default::default(),
1331 git_diff_debouncer: DebouncedDelay::new(),
1332 terminals: Terminals {
1333 local_handles: Vec::new(),
1334 },
1335 node: Some(node),
1336 search_history: Self::new_search_history(),
1337 environment,
1338 remotely_created_models: Default::default(),
1339
1340 search_included_history: Self::new_search_history(),
1341 search_excluded_history: Self::new_search_history(),
1342
1343 toolchain_store: Some(toolchain_store),
1344
1345 agent_location: None,
1346 downloading_files: Default::default(),
1347 last_worktree_paths: WorktreePaths::default(),
1348 }
1349 })
1350 }
1351
1352 pub fn remote(
1353 remote: Entity<RemoteClient>,
1354 client: Arc<Client>,
1355 node: NodeRuntime,
1356 user_store: Entity<UserStore>,
1357 languages: Arc<LanguageRegistry>,
1358 fs: Arc<dyn Fs>,
1359 init_worktree_trust: bool,
1360 cx: &mut App,
1361 ) -> Entity<Self> {
1362 cx.new(|cx: &mut Context<Self>| {
1363 let (tx, rx) = mpsc::unbounded();
1364 cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1365 .detach();
1366 let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1367
1368 let (remote_proto, path_style, connection_options) =
1369 remote.read_with(cx, |remote, _| {
1370 (
1371 remote.proto_client(),
1372 remote.path_style(),
1373 remote.connection_options(),
1374 )
1375 });
1376 let worktree_store = cx.new(|cx| {
1377 WorktreeStore::remote(
1378 false,
1379 remote_proto.clone(),
1380 REMOTE_SERVER_PROJECT_ID,
1381 path_style,
1382 WorktreeIdCounter::get(cx),
1383 )
1384 });
1385
1386 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1387 .detach();
1388 if init_worktree_trust {
1389 trusted_worktrees::track_worktree_trust(
1390 worktree_store.clone(),
1391 Some(RemoteHostLocation::from(connection_options)),
1392 None,
1393 Some((remote_proto.clone(), ProjectId(REMOTE_SERVER_PROJECT_ID))),
1394 cx,
1395 );
1396 }
1397
1398 let weak_self = cx.weak_entity();
1399
1400 let buffer_store = cx.new(|cx| {
1401 BufferStore::remote(
1402 worktree_store.clone(),
1403 remote.read(cx).proto_client(),
1404 REMOTE_SERVER_PROJECT_ID,
1405 cx,
1406 )
1407 });
1408 let image_store = cx.new(|cx| {
1409 ImageStore::remote(
1410 worktree_store.clone(),
1411 remote.read(cx).proto_client(),
1412 REMOTE_SERVER_PROJECT_ID,
1413 cx,
1414 )
1415 });
1416 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1417 .detach();
1418 let toolchain_store = cx.new(|cx| {
1419 ToolchainStore::remote(
1420 REMOTE_SERVER_PROJECT_ID,
1421 worktree_store.clone(),
1422 remote.read(cx).proto_client(),
1423 cx,
1424 )
1425 });
1426
1427 let context_server_store = cx.new(|cx| {
1428 ContextServerStore::remote(
1429 rpc::proto::REMOTE_SERVER_PROJECT_ID,
1430 remote.clone(),
1431 worktree_store.clone(),
1432 Some(weak_self.clone()),
1433 cx,
1434 )
1435 });
1436
1437 let environment = cx.new(|cx| {
1438 ProjectEnvironment::new(
1439 None,
1440 worktree_store.downgrade(),
1441 Some(remote.downgrade()),
1442 false,
1443 cx,
1444 )
1445 });
1446
1447 let lsp_store = cx.new(|cx| {
1448 LspStore::new_remote(
1449 buffer_store.clone(),
1450 worktree_store.clone(),
1451 languages.clone(),
1452 remote_proto.clone(),
1453 REMOTE_SERVER_PROJECT_ID,
1454 cx,
1455 )
1456 });
1457 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1458
1459 let breakpoint_store = cx.new(|_| {
1460 BreakpointStore::remote(
1461 REMOTE_SERVER_PROJECT_ID,
1462 remote_proto.clone(),
1463 buffer_store.clone(),
1464 worktree_store.clone(),
1465 )
1466 });
1467
1468 let dap_store = cx.new(|cx| {
1469 DapStore::new_remote(
1470 REMOTE_SERVER_PROJECT_ID,
1471 remote.clone(),
1472 breakpoint_store.clone(),
1473 worktree_store.clone(),
1474 node.clone(),
1475 client.http_client(),
1476 fs.clone(),
1477 cx,
1478 )
1479 });
1480
1481 let git_store = cx.new(|cx| {
1482 GitStore::remote(
1483 &worktree_store,
1484 buffer_store.clone(),
1485 remote_proto.clone(),
1486 REMOTE_SERVER_PROJECT_ID,
1487 cx,
1488 )
1489 });
1490
1491 let task_store = cx.new(|cx| {
1492 TaskStore::remote(
1493 buffer_store.downgrade(),
1494 worktree_store.clone(),
1495 toolchain_store.read(cx).as_language_toolchain_store(),
1496 remote.read(cx).proto_client(),
1497 REMOTE_SERVER_PROJECT_ID,
1498 git_store.clone(),
1499 cx,
1500 )
1501 });
1502
1503 let settings_observer = cx.new(|cx| {
1504 SettingsObserver::new_remote(
1505 fs.clone(),
1506 worktree_store.clone(),
1507 task_store.clone(),
1508 Some(remote_proto.clone()),
1509 false,
1510 cx,
1511 )
1512 });
1513 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1514 .detach();
1515
1516 let agent_server_store = cx.new(|_| {
1517 AgentServerStore::remote(
1518 REMOTE_SERVER_PROJECT_ID,
1519 remote.clone(),
1520 worktree_store.clone(),
1521 )
1522 });
1523
1524 cx.subscribe(&remote, Self::on_remote_client_event).detach();
1525
1526 let this = Self {
1527 buffer_ordered_messages_tx: tx,
1528 collaborators: Default::default(),
1529 worktree_store,
1530 buffer_store,
1531 image_store,
1532 lsp_store,
1533 context_server_store,
1534 breakpoint_store,
1535 dap_store,
1536 join_project_response_message_id: 0,
1537 client_state: ProjectClientState::Local,
1538 git_store,
1539 agent_server_store,
1540 client_subscriptions: Vec::new(),
1541 _subscriptions: vec![
1542 cx.on_release(Self::release),
1543 cx.on_app_quit(|this, cx| {
1544 let shutdown = this.remote_client.take().and_then(|client| {
1545 client.update(cx, |client, cx| {
1546 client.shutdown_processes(
1547 Some(proto::ShutdownRemoteServer {}),
1548 cx.background_executor().clone(),
1549 )
1550 })
1551 });
1552
1553 cx.background_executor().spawn(async move {
1554 if let Some(shutdown) = shutdown {
1555 shutdown.await;
1556 }
1557 })
1558 }),
1559 ],
1560 active_entry: None,
1561 snippets,
1562 languages,
1563 collab_client: client,
1564 task_store,
1565 user_store,
1566 settings_observer,
1567 fs,
1568 remote_client: Some(remote.clone()),
1569 buffers_needing_diff: Default::default(),
1570 git_diff_debouncer: DebouncedDelay::new(),
1571 terminals: Terminals {
1572 local_handles: Vec::new(),
1573 },
1574 node: Some(node),
1575 search_history: Self::new_search_history(),
1576 environment,
1577 remotely_created_models: Default::default(),
1578
1579 search_included_history: Self::new_search_history(),
1580 search_excluded_history: Self::new_search_history(),
1581
1582 toolchain_store: Some(toolchain_store),
1583 agent_location: None,
1584 downloading_files: Default::default(),
1585 last_worktree_paths: WorktreePaths::default(),
1586 };
1587
1588 // remote server -> local machine handlers
1589 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &cx.entity());
1590 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.buffer_store);
1591 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.worktree_store);
1592 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.lsp_store);
1593 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.dap_store);
1594 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.breakpoint_store);
1595 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.settings_observer);
1596 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.git_store);
1597 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.agent_server_store);
1598
1599 remote_proto.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1600 remote_proto.add_entity_message_handler(Self::handle_create_image_for_peer);
1601 remote_proto.add_entity_message_handler(Self::handle_create_file_for_peer);
1602 remote_proto.add_entity_message_handler(Self::handle_update_worktree);
1603 remote_proto.add_entity_message_handler(Self::handle_update_project);
1604 remote_proto.add_entity_message_handler(Self::handle_toast);
1605 remote_proto.add_entity_request_handler(Self::handle_language_server_prompt_request);
1606 remote_proto.add_entity_message_handler(Self::handle_hide_toast);
1607 remote_proto.add_entity_request_handler(Self::handle_update_buffer_from_remote_server);
1608 remote_proto.add_entity_request_handler(Self::handle_trust_worktrees);
1609 remote_proto.add_entity_request_handler(Self::handle_restrict_worktrees);
1610 remote_proto.add_entity_request_handler(Self::handle_find_search_candidates_chunk);
1611
1612 remote_proto.add_entity_message_handler(Self::handle_find_search_candidates_cancel);
1613 BufferStore::init(&remote_proto);
1614 WorktreeStore::init_remote(&remote_proto);
1615 LspStore::init(&remote_proto);
1616 SettingsObserver::init(&remote_proto);
1617 TaskStore::init(Some(&remote_proto));
1618 ToolchainStore::init(&remote_proto);
1619 DapStore::init(&remote_proto, cx);
1620 BreakpointStore::init(&remote_proto);
1621 GitStore::init(&remote_proto);
1622 AgentServerStore::init_remote(&remote_proto);
1623
1624 this
1625 })
1626 }
1627
1628 pub async fn in_room(
1629 remote_id: u64,
1630 client: Arc<Client>,
1631 user_store: Entity<UserStore>,
1632 languages: Arc<LanguageRegistry>,
1633 fs: Arc<dyn Fs>,
1634 cx: AsyncApp,
1635 ) -> Result<Entity<Self>> {
1636 client.connect(true, &cx).await.into_response()?;
1637
1638 let subscriptions = [
1639 EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
1640 EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
1641 EntitySubscription::GitStore(client.subscribe_to_entity::<GitStore>(remote_id)?),
1642 EntitySubscription::WorktreeStore(
1643 client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
1644 ),
1645 EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
1646 EntitySubscription::SettingsObserver(
1647 client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
1648 ),
1649 EntitySubscription::DapStore(client.subscribe_to_entity::<DapStore>(remote_id)?),
1650 EntitySubscription::BreakpointStore(
1651 client.subscribe_to_entity::<BreakpointStore>(remote_id)?,
1652 ),
1653 ];
1654 let committer = get_git_committer(&cx).await;
1655 let response = client
1656 .request_envelope(proto::JoinProject {
1657 project_id: remote_id,
1658 committer_email: committer.email,
1659 committer_name: committer.name,
1660 features: CURRENT_PROJECT_FEATURES
1661 .iter()
1662 .map(|s| s.to_string())
1663 .collect(),
1664 })
1665 .await?;
1666 Self::from_join_project_response(
1667 response,
1668 subscriptions,
1669 client,
1670 false,
1671 user_store,
1672 languages,
1673 fs,
1674 cx,
1675 )
1676 .await
1677 }
1678
1679 async fn from_join_project_response(
1680 response: TypedEnvelope<proto::JoinProjectResponse>,
1681 subscriptions: [EntitySubscription; 8],
1682 client: Arc<Client>,
1683 run_tasks: bool,
1684 user_store: Entity<UserStore>,
1685 languages: Arc<LanguageRegistry>,
1686 fs: Arc<dyn Fs>,
1687 mut cx: AsyncApp,
1688 ) -> Result<Entity<Self>> {
1689 let remote_id = response.payload.project_id;
1690 let role = response.payload.role();
1691
1692 let path_style = if response.payload.windows_paths {
1693 PathStyle::Windows
1694 } else {
1695 PathStyle::Posix
1696 };
1697
1698 let worktree_store = cx.new(|cx| {
1699 WorktreeStore::remote(
1700 true,
1701 client.clone().into(),
1702 response.payload.project_id,
1703 path_style,
1704 WorktreeIdCounter::get(cx),
1705 )
1706 });
1707 let buffer_store = cx.new(|cx| {
1708 BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1709 });
1710 let image_store = cx.new(|cx| {
1711 ImageStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1712 });
1713
1714 let environment =
1715 cx.new(|cx| ProjectEnvironment::new(None, worktree_store.downgrade(), None, true, cx));
1716 let breakpoint_store = cx.new(|_| {
1717 BreakpointStore::remote(
1718 remote_id,
1719 client.clone().into(),
1720 buffer_store.clone(),
1721 worktree_store.clone(),
1722 )
1723 });
1724 let dap_store = cx.new(|cx| {
1725 DapStore::new_collab(
1726 remote_id,
1727 client.clone().into(),
1728 breakpoint_store.clone(),
1729 worktree_store.clone(),
1730 fs.clone(),
1731 cx,
1732 )
1733 });
1734
1735 let lsp_store = cx.new(|cx| {
1736 LspStore::new_remote(
1737 buffer_store.clone(),
1738 worktree_store.clone(),
1739 languages.clone(),
1740 client.clone().into(),
1741 remote_id,
1742 cx,
1743 )
1744 });
1745
1746 let git_store = cx.new(|cx| {
1747 GitStore::remote(
1748 // In this remote case we pass None for the environment
1749 &worktree_store,
1750 buffer_store.clone(),
1751 client.clone().into(),
1752 remote_id,
1753 cx,
1754 )
1755 });
1756
1757 let task_store = cx.new(|cx| {
1758 if run_tasks {
1759 TaskStore::remote(
1760 buffer_store.downgrade(),
1761 worktree_store.clone(),
1762 Arc::new(EmptyToolchainStore),
1763 client.clone().into(),
1764 remote_id,
1765 git_store.clone(),
1766 cx,
1767 )
1768 } else {
1769 TaskStore::Noop
1770 }
1771 });
1772
1773 let settings_observer = cx.new(|cx| {
1774 SettingsObserver::new_remote(
1775 fs.clone(),
1776 worktree_store.clone(),
1777 task_store.clone(),
1778 None,
1779 true,
1780 cx,
1781 )
1782 });
1783
1784 let agent_server_store = cx.new(|_cx| AgentServerStore::collab());
1785 let replica_id = ReplicaId::new(response.payload.replica_id as u16);
1786
1787 let project = cx.new(|cx| {
1788 let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1789
1790 let weak_self = cx.weak_entity();
1791 let context_server_store = cx.new(|cx| {
1792 ContextServerStore::local(worktree_store.clone(), Some(weak_self), false, cx)
1793 });
1794
1795 let mut worktrees = Vec::new();
1796 for worktree in response.payload.worktrees {
1797 let worktree = Worktree::remote(
1798 remote_id,
1799 replica_id,
1800 worktree,
1801 client.clone().into(),
1802 path_style,
1803 cx,
1804 );
1805 worktrees.push(worktree);
1806 }
1807
1808 let (tx, rx) = mpsc::unbounded();
1809 cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1810 .detach();
1811
1812 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1813 .detach();
1814
1815 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1816 .detach();
1817 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1818 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1819 .detach();
1820
1821 cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1822
1823 let mut project = Self {
1824 buffer_ordered_messages_tx: tx,
1825 buffer_store: buffer_store.clone(),
1826 image_store,
1827 worktree_store: worktree_store.clone(),
1828 lsp_store: lsp_store.clone(),
1829 context_server_store,
1830 active_entry: None,
1831 collaborators: Default::default(),
1832 join_project_response_message_id: response.message_id,
1833 languages,
1834 user_store: user_store.clone(),
1835 task_store,
1836 snippets,
1837 fs,
1838 remote_client: None,
1839 settings_observer: settings_observer.clone(),
1840 client_subscriptions: Default::default(),
1841 _subscriptions: vec![cx.on_release(Self::release)],
1842 collab_client: client.clone(),
1843 client_state: ProjectClientState::Collab {
1844 sharing_has_stopped: false,
1845 capability: Capability::ReadWrite,
1846 remote_id,
1847 replica_id,
1848 },
1849 breakpoint_store: breakpoint_store.clone(),
1850 dap_store: dap_store.clone(),
1851 git_store: git_store.clone(),
1852 agent_server_store,
1853 buffers_needing_diff: Default::default(),
1854 git_diff_debouncer: DebouncedDelay::new(),
1855 terminals: Terminals {
1856 local_handles: Vec::new(),
1857 },
1858 node: None,
1859 search_history: Self::new_search_history(),
1860 search_included_history: Self::new_search_history(),
1861 search_excluded_history: Self::new_search_history(),
1862 environment,
1863 remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1864 toolchain_store: None,
1865 agent_location: None,
1866 downloading_files: Default::default(),
1867 last_worktree_paths: WorktreePaths::default(),
1868 };
1869 project.set_role(role, cx);
1870 for worktree in worktrees {
1871 project.add_worktree(&worktree, cx);
1872 }
1873 project
1874 });
1875
1876 let weak_project = project.downgrade();
1877 lsp_store.update(&mut cx, |lsp_store, cx| {
1878 lsp_store.set_language_server_statuses_from_proto(
1879 weak_project,
1880 response.payload.language_servers,
1881 response.payload.language_server_capabilities,
1882 cx,
1883 );
1884 });
1885
1886 let subscriptions = subscriptions
1887 .into_iter()
1888 .map(|s| match s {
1889 EntitySubscription::BufferStore(subscription) => {
1890 subscription.set_entity(&buffer_store, &cx)
1891 }
1892 EntitySubscription::WorktreeStore(subscription) => {
1893 subscription.set_entity(&worktree_store, &cx)
1894 }
1895 EntitySubscription::GitStore(subscription) => {
1896 subscription.set_entity(&git_store, &cx)
1897 }
1898 EntitySubscription::SettingsObserver(subscription) => {
1899 subscription.set_entity(&settings_observer, &cx)
1900 }
1901 EntitySubscription::Project(subscription) => subscription.set_entity(&project, &cx),
1902 EntitySubscription::LspStore(subscription) => {
1903 subscription.set_entity(&lsp_store, &cx)
1904 }
1905 EntitySubscription::DapStore(subscription) => {
1906 subscription.set_entity(&dap_store, &cx)
1907 }
1908 EntitySubscription::BreakpointStore(subscription) => {
1909 subscription.set_entity(&breakpoint_store, &cx)
1910 }
1911 })
1912 .collect::<Vec<_>>();
1913
1914 let user_ids = response
1915 .payload
1916 .collaborators
1917 .iter()
1918 .map(|peer| peer.user_id)
1919 .collect();
1920 user_store
1921 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
1922 .await?;
1923
1924 project.update(&mut cx, |this, cx| {
1925 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1926 this.client_subscriptions.extend(subscriptions);
1927 anyhow::Ok(())
1928 })?;
1929
1930 Ok(project)
1931 }
1932
1933 fn new_search_history() -> SearchHistory {
1934 SearchHistory::new(
1935 Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1936 search_history::QueryInsertionBehavior::AlwaysInsert,
1937 )
1938 }
1939
1940 fn release(&mut self, cx: &mut App) {
1941 if let Some(client) = self.remote_client.take() {
1942 let shutdown = client.update(cx, |client, cx| {
1943 client.shutdown_processes(
1944 Some(proto::ShutdownRemoteServer {}),
1945 cx.background_executor().clone(),
1946 )
1947 });
1948
1949 cx.background_spawn(async move {
1950 if let Some(shutdown) = shutdown {
1951 shutdown.await;
1952 }
1953 })
1954 .detach()
1955 }
1956
1957 match &self.client_state {
1958 ProjectClientState::Local => {}
1959 ProjectClientState::Shared { .. } => {
1960 let _ = self.unshare_internal(cx);
1961 }
1962 ProjectClientState::Collab { remote_id, .. } => {
1963 let _ = self.collab_client.send(proto::LeaveProject {
1964 project_id: *remote_id,
1965 });
1966 self.disconnected_from_host_internal(cx);
1967 }
1968 }
1969 }
1970
1971 #[cfg(feature = "test-support")]
1972 pub fn client_subscriptions(&self) -> &Vec<client::Subscription> {
1973 &self.client_subscriptions
1974 }
1975
1976 #[cfg(feature = "test-support")]
1977 pub async fn example(
1978 root_paths: impl IntoIterator<Item = &Path>,
1979 cx: &mut AsyncApp,
1980 ) -> Entity<Project> {
1981 use clock::FakeSystemClock;
1982
1983 let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
1984 let languages = LanguageRegistry::test(cx.background_executor().clone());
1985 let clock = Arc::new(FakeSystemClock::new());
1986 let http_client = http_client::FakeHttpClient::with_404_response();
1987 let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1988 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1989 let project = cx.update(|cx| {
1990 Project::local(
1991 client,
1992 node_runtime::NodeRuntime::unavailable(),
1993 user_store,
1994 Arc::new(languages),
1995 fs,
1996 None,
1997 LocalProjectFlags {
1998 init_worktree_trust: false,
1999 ..Default::default()
2000 },
2001 cx,
2002 )
2003 });
2004 for path in root_paths {
2005 let (tree, _): (Entity<Worktree>, _) = project
2006 .update(cx, |project, cx| {
2007 project.find_or_create_worktree(path, true, cx)
2008 })
2009 .await
2010 .unwrap();
2011 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
2012 .await;
2013 }
2014 project
2015 }
2016
2017 #[cfg(feature = "test-support")]
2018 pub async fn test(
2019 fs: Arc<dyn Fs>,
2020 root_paths: impl IntoIterator<Item = &Path>,
2021 cx: &mut gpui::TestAppContext,
2022 ) -> Entity<Project> {
2023 Self::test_project(fs, root_paths, false, cx).await
2024 }
2025
2026 #[cfg(feature = "test-support")]
2027 pub async fn test_with_worktree_trust(
2028 fs: Arc<dyn Fs>,
2029 root_paths: impl IntoIterator<Item = &Path>,
2030 cx: &mut gpui::TestAppContext,
2031 ) -> Entity<Project> {
2032 Self::test_project(fs, root_paths, true, cx).await
2033 }
2034
2035 #[cfg(feature = "test-support")]
2036 async fn test_project(
2037 fs: Arc<dyn Fs>,
2038 root_paths: impl IntoIterator<Item = &Path>,
2039 init_worktree_trust: bool,
2040 cx: &mut gpui::TestAppContext,
2041 ) -> Entity<Project> {
2042 use clock::FakeSystemClock;
2043
2044 let languages = LanguageRegistry::test(cx.executor());
2045 let clock = Arc::new(FakeSystemClock::new());
2046 let http_client = http_client::FakeHttpClient::with_404_response();
2047 let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
2048 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
2049 let project = cx.update(|cx| {
2050 Project::local(
2051 client,
2052 node_runtime::NodeRuntime::unavailable(),
2053 user_store,
2054 Arc::new(languages),
2055 fs,
2056 None,
2057 LocalProjectFlags {
2058 init_worktree_trust,
2059 ..Default::default()
2060 },
2061 cx,
2062 )
2063 });
2064 for path in root_paths {
2065 let (tree, _) = project
2066 .update(cx, |project, cx| {
2067 project.find_or_create_worktree(path, true, cx)
2068 })
2069 .await
2070 .unwrap();
2071
2072 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
2073 .await;
2074 }
2075 project
2076 }
2077
2078 #[cfg(any(test, feature = "test-support"))]
2079 pub fn add_test_remote_worktree(
2080 &mut self,
2081 abs_path: &str,
2082 cx: &mut Context<Self>,
2083 ) -> Entity<Worktree> {
2084 use rpc::NoopProtoClient;
2085 use util::paths::PathStyle;
2086
2087 let root_name = std::path::Path::new(abs_path)
2088 .file_name()
2089 .map(|n| n.to_string_lossy().to_string())
2090 .unwrap_or_default();
2091
2092 let client = AnyProtoClient::new(NoopProtoClient::new());
2093 let worktree = Worktree::remote(
2094 0,
2095 ReplicaId::new(1),
2096 proto::WorktreeMetadata {
2097 id: 100 + self.visible_worktrees(cx).count() as u64,
2098 root_name,
2099 visible: true,
2100 abs_path: abs_path.to_string(),
2101 root_repo_common_dir: None,
2102 },
2103 client,
2104 PathStyle::Posix,
2105 cx,
2106 );
2107 self.worktree_store
2108 .update(cx, |store, cx| store.add(&worktree, cx));
2109 worktree
2110 }
2111
2112 #[inline]
2113 pub fn dap_store(&self) -> Entity<DapStore> {
2114 self.dap_store.clone()
2115 }
2116
2117 #[inline]
2118 pub fn breakpoint_store(&self) -> Entity<BreakpointStore> {
2119 self.breakpoint_store.clone()
2120 }
2121
2122 pub fn active_debug_session(&self, cx: &App) -> Option<(Entity<Session>, ActiveStackFrame)> {
2123 let active_position = self.breakpoint_store.read(cx).active_position()?;
2124 let session = self
2125 .dap_store
2126 .read(cx)
2127 .session_by_id(active_position.session_id)?;
2128 Some((session, active_position.clone()))
2129 }
2130
2131 #[inline]
2132 pub fn lsp_store(&self) -> Entity<LspStore> {
2133 self.lsp_store.clone()
2134 }
2135
2136 #[inline]
2137 pub fn worktree_store(&self) -> Entity<WorktreeStore> {
2138 self.worktree_store.clone()
2139 }
2140
2141 /// Returns a future that resolves when all visible worktrees have completed
2142 /// their initial scan.
2143 pub fn wait_for_initial_scan(&self, cx: &App) -> impl Future<Output = ()> + use<> {
2144 self.worktree_store.read(cx).wait_for_initial_scan()
2145 }
2146
2147 #[inline]
2148 pub fn context_server_store(&self) -> Entity<ContextServerStore> {
2149 self.context_server_store.clone()
2150 }
2151
2152 #[inline]
2153 pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
2154 self.buffer_store.read(cx).get(remote_id)
2155 }
2156
2157 #[inline]
2158 pub fn languages(&self) -> &Arc<LanguageRegistry> {
2159 &self.languages
2160 }
2161
2162 #[inline]
2163 pub fn client(&self) -> Arc<Client> {
2164 self.collab_client.clone()
2165 }
2166
2167 #[inline]
2168 pub fn remote_client(&self) -> Option<Entity<RemoteClient>> {
2169 self.remote_client.clone()
2170 }
2171
2172 #[inline]
2173 pub fn user_store(&self) -> Entity<UserStore> {
2174 self.user_store.clone()
2175 }
2176
2177 #[inline]
2178 pub fn node_runtime(&self) -> Option<&NodeRuntime> {
2179 self.node.as_ref()
2180 }
2181
2182 #[inline]
2183 pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
2184 self.buffer_store.read(cx).buffers().collect()
2185 }
2186
2187 #[inline]
2188 pub fn environment(&self) -> &Entity<ProjectEnvironment> {
2189 &self.environment
2190 }
2191
2192 #[inline]
2193 pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
2194 self.environment.read(cx).get_cli_environment()
2195 }
2196
2197 #[inline]
2198 pub fn peek_environment_error<'a>(&'a self, cx: &'a App) -> Option<&'a String> {
2199 self.environment.read(cx).peek_environment_error()
2200 }
2201
2202 #[inline]
2203 pub fn pop_environment_error(&mut self, cx: &mut Context<Self>) {
2204 self.environment.update(cx, |environment, _| {
2205 environment.pop_environment_error();
2206 });
2207 }
2208
2209 #[cfg(feature = "test-support")]
2210 #[inline]
2211 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
2212 self.buffer_store
2213 .read(cx)
2214 .get_by_path(&path.into())
2215 .is_some()
2216 }
2217
2218 #[inline]
2219 pub fn fs(&self) -> &Arc<dyn Fs> {
2220 &self.fs
2221 }
2222
2223 #[inline]
2224 pub fn remote_id(&self) -> Option<u64> {
2225 match self.client_state {
2226 ProjectClientState::Local => None,
2227 ProjectClientState::Shared { remote_id, .. }
2228 | ProjectClientState::Collab { remote_id, .. } => Some(remote_id),
2229 }
2230 }
2231
2232 #[inline]
2233 pub fn supports_terminal(&self, _cx: &App) -> bool {
2234 if self.is_local() {
2235 return true;
2236 }
2237 if self.is_via_remote_server() {
2238 return true;
2239 }
2240
2241 false
2242 }
2243
2244 #[inline]
2245 pub fn remote_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
2246 self.remote_client
2247 .as_ref()
2248 .map(|remote| remote.read(cx).connection_state())
2249 }
2250
2251 #[inline]
2252 pub fn remote_connection_options(&self, cx: &App) -> Option<RemoteConnectionOptions> {
2253 self.remote_client
2254 .as_ref()
2255 .map(|remote| remote.read(cx).connection_options())
2256 }
2257
2258 /// Reveals the given path in the system file manager.
2259 ///
2260 /// On Windows with a WSL remote connection, this converts the POSIX path
2261 /// to a Windows UNC path before revealing.
2262 pub fn reveal_path(&self, path: &Path, cx: &mut Context<Self>) {
2263 #[cfg(target_os = "windows")]
2264 if let Some(RemoteConnectionOptions::Wsl(wsl_options)) = self.remote_connection_options(cx)
2265 {
2266 let path = path.to_path_buf();
2267 cx.spawn(async move |_, cx| {
2268 wsl_path_to_windows_path(&wsl_options, &path)
2269 .await
2270 .map(|windows_path| cx.update(|cx| cx.reveal_path(&windows_path)))
2271 })
2272 .detach_and_log_err(cx);
2273 return;
2274 }
2275
2276 cx.reveal_path(path);
2277 }
2278
2279 #[inline]
2280 pub fn replica_id(&self) -> ReplicaId {
2281 match self.client_state {
2282 ProjectClientState::Collab { replica_id, .. } => replica_id,
2283 _ => {
2284 if self.remote_client.is_some() {
2285 ReplicaId::REMOTE_SERVER
2286 } else {
2287 ReplicaId::LOCAL
2288 }
2289 }
2290 }
2291 }
2292
2293 #[inline]
2294 pub fn task_store(&self) -> &Entity<TaskStore> {
2295 &self.task_store
2296 }
2297
2298 #[inline]
2299 pub fn snippets(&self) -> &Entity<SnippetProvider> {
2300 &self.snippets
2301 }
2302
2303 #[inline]
2304 pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
2305 match kind {
2306 SearchInputKind::Query => &self.search_history,
2307 SearchInputKind::Include => &self.search_included_history,
2308 SearchInputKind::Exclude => &self.search_excluded_history,
2309 }
2310 }
2311
2312 #[inline]
2313 pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
2314 match kind {
2315 SearchInputKind::Query => &mut self.search_history,
2316 SearchInputKind::Include => &mut self.search_included_history,
2317 SearchInputKind::Exclude => &mut self.search_excluded_history,
2318 }
2319 }
2320
2321 #[inline]
2322 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
2323 &self.collaborators
2324 }
2325
2326 #[inline]
2327 pub fn host(&self) -> Option<&Collaborator> {
2328 self.collaborators.values().find(|c| c.is_host)
2329 }
2330
2331 #[inline]
2332 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
2333 self.worktree_store.update(cx, |store, _| {
2334 store.set_worktrees_reordered(worktrees_reordered);
2335 });
2336 }
2337
2338 /// Collect all worktrees, including ones that don't appear in the project panel
2339 #[inline]
2340 pub fn worktrees<'a>(
2341 &self,
2342 cx: &'a App,
2343 ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2344 self.worktree_store.read(cx).worktrees()
2345 }
2346
2347 /// Collect all user-visible worktrees, the ones that appear in the project panel.
2348 #[inline]
2349 pub fn visible_worktrees<'a>(
2350 &'a self,
2351 cx: &'a App,
2352 ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2353 self.worktree_store.read(cx).visible_worktrees(cx)
2354 }
2355
2356 pub(crate) fn default_visible_worktree_paths(
2357 worktree_store: &WorktreeStore,
2358 cx: &App,
2359 ) -> Vec<PathBuf> {
2360 worktree_store
2361 .visible_worktrees(cx)
2362 .sorted_by(|left, right| {
2363 left.read(cx)
2364 .is_single_file()
2365 .cmp(&right.read(cx).is_single_file())
2366 })
2367 .filter_map(|worktree| {
2368 let worktree = worktree.read(cx);
2369 let path = worktree.abs_path();
2370 if worktree.is_single_file() {
2371 Some(path.parent()?.to_path_buf())
2372 } else {
2373 Some(path.to_path_buf())
2374 }
2375 })
2376 .collect()
2377 }
2378
2379 pub fn default_path_list(&self, cx: &App) -> PathList {
2380 let worktree_roots =
2381 Self::default_visible_worktree_paths(&self.worktree_store.read(cx), cx);
2382
2383 if worktree_roots.is_empty() {
2384 PathList::new(&[paths::home_dir().as_path()])
2385 } else {
2386 PathList::new(&worktree_roots)
2387 }
2388 }
2389
2390 #[inline]
2391 pub fn worktree_for_root_name(&self, root_name: &str, cx: &App) -> Option<Entity<Worktree>> {
2392 self.visible_worktrees(cx)
2393 .find(|tree| tree.read(cx).root_name() == root_name)
2394 }
2395
2396 fn emit_group_key_changed_if_needed(&mut self, cx: &mut Context<Self>) {
2397 let new_worktree_paths = self.worktree_paths(cx);
2398 if new_worktree_paths != self.last_worktree_paths {
2399 let old_worktree_paths =
2400 std::mem::replace(&mut self.last_worktree_paths, new_worktree_paths);
2401 cx.emit(Event::WorktreePathsChanged { old_worktree_paths });
2402 }
2403 }
2404
2405 #[inline]
2406 pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
2407 self.visible_worktrees(cx)
2408 .map(|tree| tree.read(cx).root_name().as_unix_str())
2409 }
2410
2411 #[inline]
2412 pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
2413 self.worktree_store.read(cx).worktree_for_id(id, cx)
2414 }
2415
2416 pub fn worktree_for_entry(
2417 &self,
2418 entry_id: ProjectEntryId,
2419 cx: &App,
2420 ) -> Option<Entity<Worktree>> {
2421 self.worktree_store
2422 .read(cx)
2423 .worktree_for_entry(entry_id, cx)
2424 }
2425
2426 #[inline]
2427 pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
2428 self.worktree_for_entry(entry_id, cx)
2429 .map(|worktree| worktree.read(cx).id())
2430 }
2431
2432 /// Checks if the entry is the root of a worktree.
2433 #[inline]
2434 pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
2435 self.worktree_for_entry(entry_id, cx)
2436 .map(|worktree| {
2437 worktree
2438 .read(cx)
2439 .root_entry()
2440 .is_some_and(|e| e.id == entry_id)
2441 })
2442 .unwrap_or(false)
2443 }
2444
2445 #[inline]
2446 pub fn project_path_git_status(
2447 &self,
2448 project_path: &ProjectPath,
2449 cx: &App,
2450 ) -> Option<FileStatus> {
2451 self.git_store
2452 .read(cx)
2453 .project_path_git_status(project_path, cx)
2454 }
2455
2456 #[inline]
2457 pub fn visibility_for_paths(
2458 &self,
2459 paths: &[PathBuf],
2460 exclude_sub_dirs: bool,
2461 cx: &App,
2462 ) -> Option<bool> {
2463 paths
2464 .iter()
2465 .map(|path| self.visibility_for_path(path, exclude_sub_dirs, cx))
2466 .max()
2467 .flatten()
2468 }
2469
2470 pub fn visibility_for_path(
2471 &self,
2472 path: &Path,
2473 exclude_sub_dirs: bool,
2474 cx: &App,
2475 ) -> Option<bool> {
2476 let path = SanitizedPath::new(path).as_path();
2477 let path_style = self.path_style(cx);
2478 self.worktrees(cx)
2479 .filter_map(|worktree| {
2480 let worktree = worktree.read(cx);
2481 let abs_path = worktree.abs_path();
2482 let relative_path = path_style.strip_prefix(path, abs_path.as_ref());
2483 let is_dir = relative_path
2484 .as_ref()
2485 .and_then(|p| worktree.entry_for_path(p))
2486 .is_some_and(|e| e.is_dir());
2487 // Don't exclude the worktree root itself, only actual subdirectories
2488 let is_subdir = relative_path
2489 .as_ref()
2490 .is_some_and(|p| !p.as_ref().as_unix_str().is_empty());
2491 let contains =
2492 relative_path.is_some() && (!exclude_sub_dirs || !is_dir || !is_subdir);
2493 contains.then(|| worktree.is_visible())
2494 })
2495 .max()
2496 }
2497
2498 pub fn create_entry(
2499 &mut self,
2500 project_path: impl Into<ProjectPath>,
2501 is_directory: bool,
2502 cx: &mut Context<Self>,
2503 ) -> Task<Result<CreatedEntry>> {
2504 let project_path = project_path.into();
2505 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
2506 return Task::ready(Err(anyhow!(format!(
2507 "No worktree for path {project_path:?}"
2508 ))));
2509 };
2510 worktree.update(cx, |worktree, cx| {
2511 worktree.create_entry(project_path.path, is_directory, None, cx)
2512 })
2513 }
2514
2515 #[inline]
2516 pub fn copy_entry(
2517 &mut self,
2518 entry_id: ProjectEntryId,
2519 new_project_path: ProjectPath,
2520 cx: &mut Context<Self>,
2521 ) -> Task<Result<Option<Entry>>> {
2522 self.worktree_store.update(cx, |worktree_store, cx| {
2523 worktree_store.copy_entry(entry_id, new_project_path, cx)
2524 })
2525 }
2526
2527 /// Renames the project entry with given `entry_id`.
2528 ///
2529 /// `new_path` is a relative path to worktree root.
2530 /// If root entry is renamed then its new root name is used instead.
2531 pub fn rename_entry(
2532 &mut self,
2533 entry_id: ProjectEntryId,
2534 new_path: ProjectPath,
2535 cx: &mut Context<Self>,
2536 ) -> Task<Result<CreatedEntry>> {
2537 let worktree_store = self.worktree_store.clone();
2538 let Some((worktree, old_path, is_dir)) = worktree_store
2539 .read(cx)
2540 .worktree_and_entry_for_id(entry_id, cx)
2541 .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
2542 else {
2543 return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
2544 };
2545
2546 let worktree_id = worktree.read(cx).id();
2547 let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
2548
2549 let lsp_store = self.lsp_store().downgrade();
2550 cx.spawn(async move |project, cx| {
2551 let (old_abs_path, new_abs_path) = {
2552 let root_path = worktree.read_with(cx, |this, _| this.abs_path());
2553 let new_abs_path = if is_root_entry {
2554 root_path
2555 .parent()
2556 .unwrap()
2557 .join(new_path.path.as_std_path())
2558 } else {
2559 root_path.join(&new_path.path.as_std_path())
2560 };
2561 (root_path.join(old_path.as_std_path()), new_abs_path)
2562 };
2563 let transaction = LspStore::will_rename_entry(
2564 lsp_store.clone(),
2565 worktree_id,
2566 &old_abs_path,
2567 &new_abs_path,
2568 is_dir,
2569 cx.clone(),
2570 )
2571 .await;
2572
2573 let entry = worktree_store
2574 .update(cx, |worktree_store, cx| {
2575 worktree_store.rename_entry(entry_id, new_path.clone(), cx)
2576 })
2577 .await?;
2578
2579 project
2580 .update(cx, |_, cx| {
2581 cx.emit(Event::EntryRenamed(
2582 transaction,
2583 new_path.clone(),
2584 new_abs_path.clone(),
2585 ));
2586 })
2587 .ok();
2588
2589 lsp_store
2590 .read_with(cx, |this, _| {
2591 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
2592 })
2593 .ok();
2594 Ok(entry)
2595 })
2596 }
2597
2598 #[inline]
2599 pub fn delete_file(
2600 &mut self,
2601 path: ProjectPath,
2602 trash: bool,
2603 cx: &mut Context<Self>,
2604 ) -> Option<Task<Result<Option<TrashedEntry>>>> {
2605 let entry = self.entry_for_path(&path, cx)?;
2606 self.delete_entry(entry.id, trash, cx)
2607 }
2608
2609 #[inline]
2610 pub fn delete_entry(
2611 &mut self,
2612 entry_id: ProjectEntryId,
2613 trash: bool,
2614 cx: &mut Context<Self>,
2615 ) -> Option<Task<Result<Option<TrashedEntry>>>> {
2616 let worktree = self.worktree_for_entry(entry_id, cx)?;
2617 cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
2618 worktree.update(cx, |worktree, cx| {
2619 worktree.delete_entry(entry_id, trash, cx)
2620 })
2621 }
2622
2623 #[inline]
2624 pub fn restore_entry(
2625 &self,
2626 worktree_id: WorktreeId,
2627 trash_entry: TrashedEntry,
2628 cx: &mut Context<'_, Self>,
2629 ) -> Task<Result<ProjectPath>> {
2630 let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {
2631 return Task::ready(Err(anyhow!("No worktree for id {worktree_id:?}")));
2632 };
2633
2634 cx.spawn(async move |_, cx| {
2635 Worktree::restore_entry(trash_entry, worktree, cx)
2636 .await
2637 .map(|rel_path_buf| ProjectPath {
2638 worktree_id: worktree_id,
2639 path: Arc::from(rel_path_buf.as_rel_path()),
2640 })
2641 })
2642 }
2643
2644 #[inline]
2645 pub fn expand_entry(
2646 &mut self,
2647 worktree_id: WorktreeId,
2648 entry_id: ProjectEntryId,
2649 cx: &mut Context<Self>,
2650 ) -> Option<Task<Result<()>>> {
2651 let worktree = self.worktree_for_id(worktree_id, cx)?;
2652 worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
2653 }
2654
2655 pub fn expand_all_for_entry(
2656 &mut self,
2657 worktree_id: WorktreeId,
2658 entry_id: ProjectEntryId,
2659 cx: &mut Context<Self>,
2660 ) -> Option<Task<Result<()>>> {
2661 let worktree = self.worktree_for_id(worktree_id, cx)?;
2662 let task = worktree.update(cx, |worktree, cx| {
2663 worktree.expand_all_for_entry(entry_id, cx)
2664 });
2665 Some(cx.spawn(async move |this, cx| {
2666 task.context("no task")?.await?;
2667 this.update(cx, |_, cx| {
2668 cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
2669 })?;
2670 Ok(())
2671 }))
2672 }
2673
2674 pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2675 anyhow::ensure!(
2676 matches!(self.client_state, ProjectClientState::Local),
2677 "project was already shared"
2678 );
2679
2680 self.client_subscriptions.extend([
2681 self.collab_client
2682 .subscribe_to_entity(project_id)?
2683 .set_entity(&cx.entity(), &cx.to_async()),
2684 self.collab_client
2685 .subscribe_to_entity(project_id)?
2686 .set_entity(&self.worktree_store, &cx.to_async()),
2687 self.collab_client
2688 .subscribe_to_entity(project_id)?
2689 .set_entity(&self.buffer_store, &cx.to_async()),
2690 self.collab_client
2691 .subscribe_to_entity(project_id)?
2692 .set_entity(&self.lsp_store, &cx.to_async()),
2693 self.collab_client
2694 .subscribe_to_entity(project_id)?
2695 .set_entity(&self.settings_observer, &cx.to_async()),
2696 self.collab_client
2697 .subscribe_to_entity(project_id)?
2698 .set_entity(&self.dap_store, &cx.to_async()),
2699 self.collab_client
2700 .subscribe_to_entity(project_id)?
2701 .set_entity(&self.breakpoint_store, &cx.to_async()),
2702 self.collab_client
2703 .subscribe_to_entity(project_id)?
2704 .set_entity(&self.git_store, &cx.to_async()),
2705 ]);
2706
2707 self.buffer_store.update(cx, |buffer_store, cx| {
2708 buffer_store.shared(project_id, self.collab_client.clone().into(), cx)
2709 });
2710 self.worktree_store.update(cx, |worktree_store, cx| {
2711 worktree_store.shared(project_id, self.collab_client.clone().into(), cx);
2712 });
2713 self.lsp_store.update(cx, |lsp_store, cx| {
2714 lsp_store.shared(project_id, self.collab_client.clone().into(), cx)
2715 });
2716 self.breakpoint_store.update(cx, |breakpoint_store, _| {
2717 breakpoint_store.shared(project_id, self.collab_client.clone().into())
2718 });
2719 self.dap_store.update(cx, |dap_store, cx| {
2720 dap_store.shared(project_id, self.collab_client.clone().into(), cx);
2721 });
2722 self.task_store.update(cx, |task_store, cx| {
2723 task_store.shared(project_id, self.collab_client.clone().into(), cx);
2724 });
2725 self.settings_observer.update(cx, |settings_observer, cx| {
2726 settings_observer.shared(project_id, self.collab_client.clone().into(), cx)
2727 });
2728 self.git_store.update(cx, |git_store, cx| {
2729 git_store.shared(project_id, self.collab_client.clone().into(), cx)
2730 });
2731
2732 self.client_state = ProjectClientState::Shared {
2733 remote_id: project_id,
2734 };
2735
2736 cx.emit(Event::RemoteIdChanged(Some(project_id)));
2737 Ok(())
2738 }
2739
2740 pub fn reshared(
2741 &mut self,
2742 message: proto::ResharedProject,
2743 cx: &mut Context<Self>,
2744 ) -> Result<()> {
2745 self.buffer_store
2746 .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2747 self.set_collaborators_from_proto(message.collaborators, cx)?;
2748
2749 self.worktree_store.update(cx, |worktree_store, cx| {
2750 worktree_store.send_project_updates(cx);
2751 });
2752 if let Some(remote_id) = self.remote_id() {
2753 self.git_store.update(cx, |git_store, cx| {
2754 git_store.shared(remote_id, self.collab_client.clone().into(), cx)
2755 });
2756 }
2757 cx.emit(Event::Reshared);
2758 Ok(())
2759 }
2760
2761 pub fn rejoined(
2762 &mut self,
2763 message: proto::RejoinedProject,
2764 message_id: u32,
2765 cx: &mut Context<Self>,
2766 ) -> Result<()> {
2767 cx.update_global::<SettingsStore, _>(|store, cx| {
2768 for worktree_metadata in &message.worktrees {
2769 store
2770 .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
2771 .log_err();
2772 }
2773 });
2774
2775 self.join_project_response_message_id = message_id;
2776 self.set_worktrees_from_proto(message.worktrees, cx)?;
2777 self.set_collaborators_from_proto(message.collaborators, cx)?;
2778
2779 let project = cx.weak_entity();
2780 self.lsp_store.update(cx, |lsp_store, cx| {
2781 lsp_store.set_language_server_statuses_from_proto(
2782 project,
2783 message.language_servers,
2784 message.language_server_capabilities,
2785 cx,
2786 )
2787 });
2788 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2789 .unwrap();
2790 cx.emit(Event::Rejoined);
2791 Ok(())
2792 }
2793
2794 #[inline]
2795 pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2796 self.unshare_internal(cx)?;
2797 cx.emit(Event::RemoteIdChanged(None));
2798 Ok(())
2799 }
2800
2801 fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2802 anyhow::ensure!(
2803 !self.is_via_collab(),
2804 "attempted to unshare a remote project"
2805 );
2806
2807 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2808 self.client_state = ProjectClientState::Local;
2809 self.collaborators.clear();
2810 self.client_subscriptions.clear();
2811 self.worktree_store.update(cx, |store, cx| {
2812 store.unshared(cx);
2813 });
2814 self.buffer_store.update(cx, |buffer_store, cx| {
2815 buffer_store.forget_shared_buffers();
2816 buffer_store.unshared(cx)
2817 });
2818 self.task_store.update(cx, |task_store, cx| {
2819 task_store.unshared(cx);
2820 });
2821 self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2822 breakpoint_store.unshared(cx);
2823 });
2824 self.dap_store.update(cx, |dap_store, cx| {
2825 dap_store.unshared(cx);
2826 });
2827 self.settings_observer.update(cx, |settings_observer, cx| {
2828 settings_observer.unshared(cx);
2829 });
2830 self.git_store.update(cx, |git_store, cx| {
2831 git_store.unshared(cx);
2832 });
2833
2834 self.collab_client
2835 .send(proto::UnshareProject {
2836 project_id: remote_id,
2837 })
2838 .ok();
2839 Ok(())
2840 } else {
2841 anyhow::bail!("attempted to unshare an unshared project");
2842 }
2843 }
2844
2845 pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2846 if self.is_disconnected(cx) {
2847 return;
2848 }
2849 self.disconnected_from_host_internal(cx);
2850 cx.emit(Event::DisconnectedFromHost);
2851 }
2852
2853 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2854 let new_capability =
2855 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2856 Capability::ReadWrite
2857 } else {
2858 Capability::ReadOnly
2859 };
2860 if let ProjectClientState::Collab { capability, .. } = &mut self.client_state {
2861 if *capability == new_capability {
2862 return;
2863 }
2864
2865 *capability = new_capability;
2866 for buffer in self.opened_buffers(cx) {
2867 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2868 }
2869 }
2870 }
2871
2872 fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2873 if let ProjectClientState::Collab {
2874 sharing_has_stopped,
2875 ..
2876 } = &mut self.client_state
2877 {
2878 *sharing_has_stopped = true;
2879 self.client_subscriptions.clear();
2880 self.collaborators.clear();
2881 self.worktree_store.update(cx, |store, cx| {
2882 store.disconnected_from_host(cx);
2883 });
2884 self.buffer_store.update(cx, |buffer_store, cx| {
2885 buffer_store.disconnected_from_host(cx)
2886 });
2887 self.lsp_store
2888 .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2889 }
2890 }
2891
2892 #[inline]
2893 pub fn close(&mut self, cx: &mut Context<Self>) {
2894 cx.emit(Event::Closed);
2895 }
2896
2897 #[inline]
2898 pub fn is_disconnected(&self, cx: &App) -> bool {
2899 match &self.client_state {
2900 ProjectClientState::Collab {
2901 sharing_has_stopped,
2902 ..
2903 } => *sharing_has_stopped,
2904 ProjectClientState::Local if self.is_via_remote_server() => {
2905 self.remote_client_is_disconnected(cx)
2906 }
2907 _ => false,
2908 }
2909 }
2910
2911 #[inline]
2912 fn remote_client_is_disconnected(&self, cx: &App) -> bool {
2913 self.remote_client
2914 .as_ref()
2915 .map(|remote| remote.read(cx).is_disconnected())
2916 .unwrap_or(false)
2917 }
2918
2919 #[inline]
2920 pub fn capability(&self) -> Capability {
2921 match &self.client_state {
2922 ProjectClientState::Collab { capability, .. } => *capability,
2923 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2924 }
2925 }
2926
2927 #[inline]
2928 pub fn is_read_only(&self, cx: &App) -> bool {
2929 self.is_disconnected(cx) || !self.capability().editable()
2930 }
2931
2932 #[inline]
2933 pub fn is_local(&self) -> bool {
2934 match &self.client_state {
2935 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2936 self.remote_client.is_none()
2937 }
2938 ProjectClientState::Collab { .. } => false,
2939 }
2940 }
2941
2942 /// Whether this project is a remote server (not counting collab).
2943 #[inline]
2944 pub fn is_via_remote_server(&self) -> bool {
2945 match &self.client_state {
2946 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2947 self.remote_client.is_some()
2948 }
2949 ProjectClientState::Collab { .. } => false,
2950 }
2951 }
2952
2953 /// Whether this project is from collab (not counting remote servers).
2954 #[inline]
2955 pub fn is_via_collab(&self) -> bool {
2956 match &self.client_state {
2957 ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2958 ProjectClientState::Collab { .. } => true,
2959 }
2960 }
2961
2962 /// `!self.is_local()`
2963 #[inline]
2964 pub fn is_remote(&self) -> bool {
2965 debug_assert_eq!(
2966 !self.is_local(),
2967 self.is_via_collab() || self.is_via_remote_server()
2968 );
2969 !self.is_local()
2970 }
2971
2972 #[inline]
2973 pub fn is_via_wsl_with_host_interop(&self, cx: &App) -> bool {
2974 match &self.client_state {
2975 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2976 matches!(
2977 &self.remote_client, Some(remote_client)
2978 if remote_client.read(cx).has_wsl_interop()
2979 )
2980 }
2981 _ => false,
2982 }
2983 }
2984
2985 pub fn disable_worktree_scanner(&mut self, cx: &mut Context<Self>) {
2986 self.worktree_store.update(cx, |worktree_store, _cx| {
2987 worktree_store.disable_scanner();
2988 });
2989 }
2990
2991 #[inline]
2992 pub fn create_buffer(
2993 &mut self,
2994 language: Option<Arc<Language>>,
2995 project_searchable: bool,
2996 cx: &mut Context<Self>,
2997 ) -> Task<Result<Entity<Buffer>>> {
2998 self.buffer_store.update(cx, |buffer_store, cx| {
2999 buffer_store.create_buffer(language, project_searchable, cx)
3000 })
3001 }
3002
3003 #[inline]
3004 pub fn create_local_buffer(
3005 &mut self,
3006 text: &str,
3007 language: Option<Arc<Language>>,
3008 project_searchable: bool,
3009 cx: &mut Context<Self>,
3010 ) -> Entity<Buffer> {
3011 if self.is_remote() {
3012 panic!("called create_local_buffer on a remote project")
3013 }
3014 self.buffer_store.update(cx, |buffer_store, cx| {
3015 buffer_store.create_local_buffer(text, language, project_searchable, cx)
3016 })
3017 }
3018
3019 pub fn open_path(
3020 &mut self,
3021 path: ProjectPath,
3022 cx: &mut Context<Self>,
3023 ) -> Task<Result<(Option<ProjectEntryId>, Entity<Buffer>)>> {
3024 let task = self.open_buffer(path, cx);
3025 cx.spawn(async move |_project, cx| {
3026 let buffer = task.await?;
3027 let project_entry_id = buffer.read_with(cx, |buffer, _cx| {
3028 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id())
3029 });
3030
3031 Ok((project_entry_id, buffer))
3032 })
3033 }
3034
3035 pub fn open_local_buffer(
3036 &mut self,
3037 abs_path: impl AsRef<Path>,
3038 cx: &mut Context<Self>,
3039 ) -> Task<Result<Entity<Buffer>>> {
3040 let worktree_task = self.find_or_create_worktree(abs_path.as_ref(), false, cx);
3041 cx.spawn(async move |this, cx| {
3042 let (worktree, relative_path) = worktree_task.await?;
3043 this.update(cx, |this, cx| {
3044 this.open_buffer((worktree.read(cx).id(), relative_path), cx)
3045 })?
3046 .await
3047 })
3048 }
3049
3050 #[cfg(feature = "test-support")]
3051 pub fn open_local_buffer_with_lsp(
3052 &mut self,
3053 abs_path: impl AsRef<Path>,
3054 cx: &mut Context<Self>,
3055 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
3056 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
3057 self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
3058 } else {
3059 Task::ready(Err(anyhow!("no such path")))
3060 }
3061 }
3062
3063 pub fn download_file(
3064 &mut self,
3065 worktree_id: WorktreeId,
3066 path: Arc<RelPath>,
3067 destination_path: PathBuf,
3068 cx: &mut Context<Self>,
3069 ) -> Task<Result<()>> {
3070 log::debug!(
3071 "download_file called: worktree_id={:?}, path={:?}, destination={:?}",
3072 worktree_id,
3073 path,
3074 destination_path
3075 );
3076
3077 let Some(remote_client) = &self.remote_client else {
3078 log::error!("download_file: not a remote project");
3079 return Task::ready(Err(anyhow!("not a remote project")));
3080 };
3081
3082 let proto_client = remote_client.read(cx).proto_client();
3083 // For SSH remote projects, use REMOTE_SERVER_PROJECT_ID instead of remote_id()
3084 // because SSH projects have client_state: Local but still need to communicate with remote server
3085 let project_id = self.remote_id().unwrap_or(REMOTE_SERVER_PROJECT_ID);
3086 let downloading_files = self.downloading_files.clone();
3087 let path_str = path.to_proto();
3088
3089 static NEXT_FILE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
3090 let file_id = NEXT_FILE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
3091
3092 // Register BEFORE sending request to avoid race condition
3093 let key = (worktree_id, path_str.clone());
3094 log::debug!(
3095 "download_file: pre-registering download with key={:?}, file_id={}",
3096 key,
3097 file_id
3098 );
3099 downloading_files.lock().insert(
3100 key,
3101 DownloadingFile {
3102 destination_path: destination_path,
3103 chunks: Vec::new(),
3104 total_size: 0,
3105 file_id: Some(file_id),
3106 },
3107 );
3108 log::debug!(
3109 "download_file: sending DownloadFileByPath request, path_str={}",
3110 path_str
3111 );
3112
3113 cx.spawn(async move |_this, _cx| {
3114 log::debug!("download_file: sending request with file_id={}...", file_id);
3115 let response = proto_client
3116 .request(proto::DownloadFileByPath {
3117 project_id,
3118 worktree_id: worktree_id.to_proto(),
3119 path: path_str.clone(),
3120 file_id,
3121 })
3122 .await?;
3123
3124 log::debug!("download_file: got response, file_id={}", response.file_id);
3125 // The file_id is set from the State message, we just confirm the request succeeded
3126 Ok(())
3127 })
3128 }
3129
3130 #[ztracing::instrument(skip_all)]
3131 pub fn open_buffer(
3132 &mut self,
3133 path: impl Into<ProjectPath>,
3134 cx: &mut App,
3135 ) -> Task<Result<Entity<Buffer>>> {
3136 if self.is_disconnected(cx) {
3137 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3138 }
3139
3140 self.buffer_store.update(cx, |buffer_store, cx| {
3141 buffer_store.open_buffer(path.into(), cx)
3142 })
3143 }
3144
3145 #[cfg(feature = "test-support")]
3146 pub fn open_buffer_with_lsp(
3147 &mut self,
3148 path: impl Into<ProjectPath>,
3149 cx: &mut Context<Self>,
3150 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
3151 let buffer = self.open_buffer(path, cx);
3152 cx.spawn(async move |this, cx| {
3153 let buffer = buffer.await?;
3154 let handle = this.update(cx, |project, cx| {
3155 project.register_buffer_with_language_servers(&buffer, cx)
3156 })?;
3157 Ok((buffer, handle))
3158 })
3159 }
3160
3161 pub fn register_buffer_with_language_servers(
3162 &self,
3163 buffer: &Entity<Buffer>,
3164 cx: &mut App,
3165 ) -> OpenLspBufferHandle {
3166 self.lsp_store.update(cx, |lsp_store, cx| {
3167 lsp_store.register_buffer_with_language_servers(buffer, HashSet::default(), false, cx)
3168 })
3169 }
3170
3171 pub fn open_unstaged_diff(
3172 &mut self,
3173 buffer: Entity<Buffer>,
3174 cx: &mut Context<Self>,
3175 ) -> Task<Result<Entity<BufferDiff>>> {
3176 if self.is_disconnected(cx) {
3177 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3178 }
3179 self.git_store
3180 .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
3181 }
3182
3183 #[ztracing::instrument(skip_all)]
3184 pub fn open_uncommitted_diff(
3185 &mut self,
3186 buffer: Entity<Buffer>,
3187 cx: &mut Context<Self>,
3188 ) -> Task<Result<Entity<BufferDiff>>> {
3189 if self.is_disconnected(cx) {
3190 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3191 }
3192 self.git_store.update(cx, |git_store, cx| {
3193 git_store.open_uncommitted_diff(buffer, cx)
3194 })
3195 }
3196
3197 pub fn open_buffer_by_id(
3198 &mut self,
3199 id: BufferId,
3200 cx: &mut Context<Self>,
3201 ) -> Task<Result<Entity<Buffer>>> {
3202 if let Some(buffer) = self.buffer_for_id(id, cx) {
3203 Task::ready(Ok(buffer))
3204 } else if self.is_local() || self.is_via_remote_server() {
3205 Task::ready(Err(anyhow!("buffer {id} does not exist")))
3206 } else if let Some(project_id) = self.remote_id() {
3207 let request = self.collab_client.request(proto::OpenBufferById {
3208 project_id,
3209 id: id.into(),
3210 });
3211 cx.spawn(async move |project, cx| {
3212 let buffer_id = BufferId::new(request.await?.buffer_id)?;
3213 project
3214 .update(cx, |project, cx| {
3215 project.buffer_store.update(cx, |buffer_store, cx| {
3216 buffer_store.wait_for_remote_buffer(buffer_id, cx)
3217 })
3218 })?
3219 .await
3220 })
3221 } else {
3222 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
3223 }
3224 }
3225
3226 pub fn save_buffers(
3227 &self,
3228 buffers: HashSet<Entity<Buffer>>,
3229 cx: &mut Context<Self>,
3230 ) -> Task<Result<()>> {
3231 cx.spawn(async move |this, cx| {
3232 let save_tasks = buffers.into_iter().filter_map(|buffer| {
3233 this.update(cx, |this, cx| this.save_buffer(buffer, cx))
3234 .ok()
3235 });
3236 try_join_all(save_tasks).await?;
3237 Ok(())
3238 })
3239 }
3240
3241 pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
3242 self.buffer_store
3243 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
3244 }
3245
3246 pub fn save_buffer_as(
3247 &mut self,
3248 buffer: Entity<Buffer>,
3249 path: ProjectPath,
3250 cx: &mut Context<Self>,
3251 ) -> Task<Result<()>> {
3252 self.buffer_store.update(cx, |buffer_store, cx| {
3253 buffer_store.save_buffer_as(buffer.clone(), path, cx)
3254 })
3255 }
3256
3257 pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
3258 self.buffer_store.read(cx).get_by_path(path)
3259 }
3260
3261 fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3262 {
3263 let mut remotely_created_models = self.remotely_created_models.lock();
3264 if remotely_created_models.retain_count > 0 {
3265 remotely_created_models.buffers.push(buffer.clone())
3266 }
3267 }
3268
3269 self.request_buffer_diff_recalculation(buffer, cx);
3270
3271 cx.subscribe(buffer, |this, buffer, event, cx| {
3272 this.on_buffer_event(buffer, event, cx);
3273 })
3274 .detach();
3275
3276 Ok(())
3277 }
3278
3279 pub fn open_image(
3280 &mut self,
3281 path: impl Into<ProjectPath>,
3282 cx: &mut Context<Self>,
3283 ) -> Task<Result<Entity<ImageItem>>> {
3284 if self.is_disconnected(cx) {
3285 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3286 }
3287
3288 let open_image_task = self.image_store.update(cx, |image_store, cx| {
3289 image_store.open_image(path.into(), cx)
3290 });
3291
3292 let weak_project = cx.entity().downgrade();
3293 cx.spawn(async move |_, cx| {
3294 let image_item = open_image_task.await?;
3295
3296 // Check if metadata already exists (e.g., for remote images)
3297 let needs_metadata =
3298 cx.read_entity(&image_item, |item, _| item.image_metadata.is_none());
3299
3300 if needs_metadata {
3301 let project = weak_project.upgrade().context("Project dropped")?;
3302 let metadata =
3303 ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
3304 image_item.update(cx, |image_item, cx| {
3305 image_item.image_metadata = Some(metadata);
3306 cx.emit(ImageItemEvent::MetadataUpdated);
3307 });
3308 }
3309
3310 Ok(image_item)
3311 })
3312 }
3313
3314 async fn send_buffer_ordered_messages(
3315 project: WeakEntity<Self>,
3316 rx: UnboundedReceiver<BufferOrderedMessage>,
3317 cx: &mut AsyncApp,
3318 ) -> Result<()> {
3319 const MAX_BATCH_SIZE: usize = 128;
3320
3321 let mut operations_by_buffer_id = HashMap::default();
3322 async fn flush_operations(
3323 this: &WeakEntity<Project>,
3324 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
3325 needs_resync_with_host: &mut bool,
3326 is_local: bool,
3327 cx: &mut AsyncApp,
3328 ) -> Result<()> {
3329 for (buffer_id, operations) in operations_by_buffer_id.drain() {
3330 let request = this.read_with(cx, |this, _| {
3331 let project_id = this.remote_id()?;
3332 Some(this.collab_client.request(proto::UpdateBuffer {
3333 buffer_id: buffer_id.into(),
3334 project_id,
3335 operations,
3336 }))
3337 })?;
3338 if let Some(request) = request
3339 && request.await.is_err()
3340 && !is_local
3341 {
3342 *needs_resync_with_host = true;
3343 break;
3344 }
3345 }
3346 Ok(())
3347 }
3348
3349 let mut needs_resync_with_host = false;
3350 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
3351
3352 while let Some(changes) = changes.next().await {
3353 let is_local = project.read_with(cx, |this, _| this.is_local())?;
3354
3355 for change in changes {
3356 match change {
3357 BufferOrderedMessage::Operation {
3358 buffer_id,
3359 operation,
3360 } => {
3361 if needs_resync_with_host {
3362 continue;
3363 }
3364
3365 operations_by_buffer_id
3366 .entry(buffer_id)
3367 .or_insert(Vec::new())
3368 .push(operation);
3369 }
3370
3371 BufferOrderedMessage::Resync => {
3372 operations_by_buffer_id.clear();
3373 if project
3374 .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
3375 .await
3376 .is_ok()
3377 {
3378 needs_resync_with_host = false;
3379 }
3380 }
3381
3382 BufferOrderedMessage::LanguageServerUpdate {
3383 language_server_id,
3384 message,
3385 name,
3386 } => {
3387 flush_operations(
3388 &project,
3389 &mut operations_by_buffer_id,
3390 &mut needs_resync_with_host,
3391 is_local,
3392 cx,
3393 )
3394 .await?;
3395
3396 project.read_with(cx, |project, _| {
3397 if let Some(project_id) = project.remote_id() {
3398 project
3399 .collab_client
3400 .send(proto::UpdateLanguageServer {
3401 project_id,
3402 server_name: name.map(|name| String::from(name.0)),
3403 language_server_id: language_server_id.to_proto(),
3404 variant: Some(message),
3405 })
3406 .log_err();
3407 }
3408 })?;
3409 }
3410 }
3411 }
3412
3413 flush_operations(
3414 &project,
3415 &mut operations_by_buffer_id,
3416 &mut needs_resync_with_host,
3417 is_local,
3418 cx,
3419 )
3420 .await?;
3421 }
3422
3423 Ok(())
3424 }
3425
3426 fn on_buffer_store_event(
3427 &mut self,
3428 _: Entity<BufferStore>,
3429 event: &BufferStoreEvent,
3430 cx: &mut Context<Self>,
3431 ) {
3432 match event {
3433 BufferStoreEvent::BufferAdded(buffer) => {
3434 self.register_buffer(buffer, cx).log_err();
3435 }
3436 BufferStoreEvent::BufferDropped(buffer_id) => {
3437 if let Some(ref remote_client) = self.remote_client {
3438 remote_client
3439 .read(cx)
3440 .proto_client()
3441 .send(proto::CloseBuffer {
3442 project_id: 0,
3443 buffer_id: buffer_id.to_proto(),
3444 })
3445 .log_err();
3446 }
3447 }
3448 _ => {}
3449 }
3450 }
3451
3452 fn on_image_store_event(
3453 &mut self,
3454 _: Entity<ImageStore>,
3455 event: &ImageStoreEvent,
3456 cx: &mut Context<Self>,
3457 ) {
3458 match event {
3459 ImageStoreEvent::ImageAdded(image) => {
3460 cx.subscribe(image, |this, image, event, cx| {
3461 this.on_image_event(image, event, cx);
3462 })
3463 .detach();
3464 }
3465 }
3466 }
3467
3468 fn on_dap_store_event(
3469 &mut self,
3470 _: Entity<DapStore>,
3471 event: &DapStoreEvent,
3472 cx: &mut Context<Self>,
3473 ) {
3474 if let DapStoreEvent::Notification(message) = event {
3475 cx.emit(Event::Toast {
3476 notification_id: "dap".into(),
3477 message: message.clone(),
3478 link: None,
3479 });
3480 }
3481 }
3482
3483 fn on_lsp_store_event(
3484 &mut self,
3485 _: Entity<LspStore>,
3486 event: &LspStoreEvent,
3487 cx: &mut Context<Self>,
3488 ) {
3489 match event {
3490 LspStoreEvent::DiagnosticsUpdated { server_id, paths } => {
3491 cx.emit(Event::DiagnosticsUpdated {
3492 paths: paths.clone(),
3493 language_server_id: *server_id,
3494 })
3495 }
3496 LspStoreEvent::LanguageServerAdded(server_id, name, worktree_id) => cx.emit(
3497 Event::LanguageServerAdded(*server_id, name.clone(), *worktree_id),
3498 ),
3499 LspStoreEvent::LanguageServerRemoved(server_id) => {
3500 cx.emit(Event::LanguageServerRemoved(*server_id))
3501 }
3502 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
3503 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
3504 ),
3505 LspStoreEvent::LanguageDetected {
3506 buffer,
3507 new_language,
3508 } => {
3509 let Some(_) = new_language else {
3510 cx.emit(Event::LanguageNotFound(buffer.clone()));
3511 return;
3512 };
3513 }
3514 LspStoreEvent::RefreshInlayHints {
3515 server_id,
3516 request_id,
3517 } => cx.emit(Event::RefreshInlayHints {
3518 server_id: *server_id,
3519 request_id: *request_id,
3520 }),
3521 LspStoreEvent::RefreshSemanticTokens {
3522 server_id,
3523 request_id,
3524 } => cx.emit(Event::RefreshSemanticTokens {
3525 server_id: *server_id,
3526 request_id: *request_id,
3527 }),
3528 LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
3529 LspStoreEvent::LanguageServerPrompt(prompt) => {
3530 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
3531 }
3532 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
3533 cx.emit(Event::DiskBasedDiagnosticsStarted {
3534 language_server_id: *language_server_id,
3535 });
3536 }
3537 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
3538 cx.emit(Event::DiskBasedDiagnosticsFinished {
3539 language_server_id: *language_server_id,
3540 });
3541 }
3542 LspStoreEvent::LanguageServerUpdate {
3543 language_server_id,
3544 name,
3545 message,
3546 } => {
3547 if self.is_local() {
3548 self.enqueue_buffer_ordered_message(
3549 BufferOrderedMessage::LanguageServerUpdate {
3550 language_server_id: *language_server_id,
3551 message: message.clone(),
3552 name: name.clone(),
3553 },
3554 )
3555 .ok();
3556 }
3557
3558 match message {
3559 proto::update_language_server::Variant::MetadataUpdated(update) => {
3560 self.lsp_store.update(cx, |lsp_store, _| {
3561 if let Some(capabilities) = update
3562 .capabilities
3563 .as_ref()
3564 .and_then(|capabilities| serde_json::from_str(capabilities).ok())
3565 {
3566 lsp_store
3567 .lsp_server_capabilities
3568 .insert(*language_server_id, capabilities);
3569 }
3570
3571 if let Some(language_server_status) = lsp_store
3572 .language_server_statuses
3573 .get_mut(language_server_id)
3574 {
3575 if let Some(binary) = &update.binary {
3576 language_server_status.binary = Some(LanguageServerBinary {
3577 path: PathBuf::from(&binary.path),
3578 arguments: binary
3579 .arguments
3580 .iter()
3581 .map(OsString::from)
3582 .collect(),
3583 env: None,
3584 });
3585 }
3586
3587 language_server_status.configuration = update
3588 .configuration
3589 .as_ref()
3590 .and_then(|config_str| serde_json::from_str(config_str).ok());
3591
3592 language_server_status.workspace_folders = update
3593 .workspace_folders
3594 .iter()
3595 .filter_map(|uri_str| lsp::Uri::from_str(uri_str).ok())
3596 .collect();
3597 }
3598 });
3599 }
3600 proto::update_language_server::Variant::RegisteredForBuffer(update) => {
3601 if let Some(buffer_id) = BufferId::new(update.buffer_id).ok() {
3602 cx.emit(Event::LanguageServerBufferRegistered {
3603 buffer_id,
3604 server_id: *language_server_id,
3605 buffer_abs_path: PathBuf::from(&update.buffer_abs_path),
3606 name: name.clone(),
3607 });
3608 }
3609 }
3610 _ => (),
3611 }
3612 }
3613 LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
3614 notification_id: "lsp".into(),
3615 message: message.clone(),
3616 link: None,
3617 }),
3618 LspStoreEvent::SnippetEdit {
3619 buffer_id,
3620 edits,
3621 most_recent_edit,
3622 } => {
3623 if most_recent_edit.replica_id == self.replica_id() {
3624 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
3625 }
3626 }
3627 LspStoreEvent::WorkspaceEditApplied(transaction) => {
3628 cx.emit(Event::WorkspaceEditApplied(transaction.clone()))
3629 }
3630 }
3631 }
3632
3633 fn on_remote_client_event(
3634 &mut self,
3635 _: Entity<RemoteClient>,
3636 event: &remote::RemoteClientEvent,
3637 cx: &mut Context<Self>,
3638 ) {
3639 match event {
3640 &remote::RemoteClientEvent::Disconnected { server_not_running } => {
3641 self.worktree_store.update(cx, |store, cx| {
3642 store.disconnected_from_host(cx);
3643 });
3644 self.buffer_store.update(cx, |buffer_store, cx| {
3645 buffer_store.disconnected_from_host(cx)
3646 });
3647 self.lsp_store.update(cx, |lsp_store, _cx| {
3648 lsp_store.disconnected_from_ssh_remote()
3649 });
3650 cx.emit(Event::DisconnectedFromRemote { server_not_running });
3651 }
3652 }
3653 }
3654
3655 fn on_settings_observer_event(
3656 &mut self,
3657 _: Entity<SettingsObserver>,
3658 event: &SettingsObserverEvent,
3659 cx: &mut Context<Self>,
3660 ) {
3661 match event {
3662 SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
3663 Err(InvalidSettingsError::LocalSettings { message, path }) => {
3664 let message = format!("Failed to set local settings in {path:?}:\n{message}");
3665 cx.emit(Event::Toast {
3666 notification_id: format!("local-settings-{path:?}").into(),
3667 link: None,
3668 message,
3669 });
3670 }
3671 Ok(path) => cx.emit(Event::HideToast {
3672 notification_id: format!("local-settings-{path:?}").into(),
3673 }),
3674 Err(_) => {}
3675 },
3676 SettingsObserverEvent::LocalTasksUpdated(result) => match result {
3677 Err(InvalidSettingsError::Tasks { message, path }) => {
3678 let message = format!("Failed to set local tasks in {path:?}:\n{message}");
3679 cx.emit(Event::Toast {
3680 notification_id: format!("local-tasks-{path:?}").into(),
3681 link: Some(ToastLink {
3682 label: "Open Tasks Documentation",
3683 url: "https://zed.dev/docs/tasks",
3684 }),
3685 message,
3686 });
3687 }
3688 Ok(path) => cx.emit(Event::HideToast {
3689 notification_id: format!("local-tasks-{path:?}").into(),
3690 }),
3691 Err(_) => {}
3692 },
3693 SettingsObserverEvent::LocalDebugScenariosUpdated(result) => match result {
3694 Err(InvalidSettingsError::Debug { message, path }) => {
3695 let message =
3696 format!("Failed to set local debug scenarios in {path:?}:\n{message}");
3697 cx.emit(Event::Toast {
3698 notification_id: format!("local-debug-scenarios-{path:?}").into(),
3699 link: None,
3700 message,
3701 });
3702 }
3703 Ok(path) => cx.emit(Event::HideToast {
3704 notification_id: format!("local-debug-scenarios-{path:?}").into(),
3705 }),
3706 Err(_) => {}
3707 },
3708 }
3709 }
3710
3711 fn on_worktree_store_event(
3712 &mut self,
3713 _: Entity<WorktreeStore>,
3714 event: &WorktreeStoreEvent,
3715 cx: &mut Context<Self>,
3716 ) {
3717 match event {
3718 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3719 self.on_worktree_added(worktree, cx);
3720 cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
3721 self.emit_group_key_changed_if_needed(cx);
3722 }
3723 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
3724 cx.emit(Event::WorktreeRemoved(*id));
3725 self.emit_group_key_changed_if_needed(cx);
3726 }
3727 WorktreeStoreEvent::WorktreeReleased(_, id) => {
3728 self.on_worktree_released(*id, cx);
3729 }
3730 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
3731 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
3732 WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
3733 self.client()
3734 .telemetry()
3735 .report_discovered_project_type_events(*worktree_id, changes);
3736 cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
3737 }
3738 WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
3739 cx.emit(Event::DeletedEntry(*worktree_id, *id))
3740 }
3741 // Listen to the GitStore instead.
3742 WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
3743 WorktreeStoreEvent::WorktreeUpdatedRootRepoCommonDir(worktree_id) => {
3744 cx.emit(Event::WorktreeUpdatedRootRepoCommonDir(*worktree_id));
3745 self.emit_group_key_changed_if_needed(cx);
3746 }
3747 }
3748 }
3749
3750 fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
3751 let mut remotely_created_models = self.remotely_created_models.lock();
3752 if remotely_created_models.retain_count > 0 {
3753 remotely_created_models.worktrees.push(worktree.clone())
3754 }
3755 }
3756
3757 fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3758 if let Some(remote) = &self.remote_client {
3759 remote
3760 .read(cx)
3761 .proto_client()
3762 .send(proto::RemoveWorktree {
3763 worktree_id: id_to_remove.to_proto(),
3764 })
3765 .log_err();
3766 }
3767 }
3768
3769 fn on_buffer_event(
3770 &mut self,
3771 buffer: Entity<Buffer>,
3772 event: &BufferEvent,
3773 cx: &mut Context<Self>,
3774 ) -> Option<()> {
3775 if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
3776 self.request_buffer_diff_recalculation(&buffer, cx);
3777 }
3778
3779 if matches!(event, BufferEvent::Edited { .. }) {
3780 cx.emit(Event::BufferEdited);
3781 }
3782
3783 let buffer_id = buffer.read(cx).remote_id();
3784 match event {
3785 BufferEvent::ReloadNeeded => {
3786 if !self.is_via_collab() {
3787 self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
3788 .detach_and_log_err(cx);
3789 }
3790 }
3791 BufferEvent::Operation {
3792 operation,
3793 is_local: true,
3794 } => {
3795 let operation = language::proto::serialize_operation(operation);
3796
3797 if let Some(remote) = &self.remote_client {
3798 remote
3799 .read(cx)
3800 .proto_client()
3801 .send(proto::UpdateBuffer {
3802 project_id: 0,
3803 buffer_id: buffer_id.to_proto(),
3804 operations: vec![operation.clone()],
3805 })
3806 .ok();
3807 }
3808
3809 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
3810 buffer_id,
3811 operation,
3812 })
3813 .ok();
3814 }
3815
3816 _ => {}
3817 }
3818
3819 None
3820 }
3821
3822 fn on_image_event(
3823 &mut self,
3824 image: Entity<ImageItem>,
3825 event: &ImageItemEvent,
3826 cx: &mut Context<Self>,
3827 ) -> Option<()> {
3828 // TODO: handle image events from remote
3829 if let ImageItemEvent::ReloadNeeded = event
3830 && !self.is_via_collab()
3831 {
3832 self.reload_images([image].into_iter().collect(), cx)
3833 .detach_and_log_err(cx);
3834 }
3835
3836 None
3837 }
3838
3839 fn request_buffer_diff_recalculation(
3840 &mut self,
3841 buffer: &Entity<Buffer>,
3842 cx: &mut Context<Self>,
3843 ) {
3844 self.buffers_needing_diff.insert(buffer.downgrade());
3845 let first_insertion = self.buffers_needing_diff.len() == 1;
3846 let settings = ProjectSettings::get_global(cx);
3847 let delay = settings.git.gutter_debounce;
3848
3849 if delay == 0 {
3850 if first_insertion {
3851 let this = cx.weak_entity();
3852 cx.defer(move |cx| {
3853 if let Some(this) = this.upgrade() {
3854 this.update(cx, |this, cx| {
3855 this.recalculate_buffer_diffs(cx).detach();
3856 });
3857 }
3858 });
3859 }
3860 return;
3861 }
3862
3863 const MIN_DELAY: u64 = 50;
3864 let delay = delay.max(MIN_DELAY);
3865 let duration = Duration::from_millis(delay);
3866
3867 self.git_diff_debouncer
3868 .fire_new(duration, cx, move |this, cx| {
3869 this.recalculate_buffer_diffs(cx)
3870 });
3871 }
3872
3873 fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
3874 cx.spawn(async move |this, cx| {
3875 loop {
3876 let task = this
3877 .update(cx, |this, cx| {
3878 let buffers = this
3879 .buffers_needing_diff
3880 .drain()
3881 .filter_map(|buffer| buffer.upgrade())
3882 .collect::<Vec<_>>();
3883 if buffers.is_empty() {
3884 None
3885 } else {
3886 Some(this.git_store.update(cx, |git_store, cx| {
3887 git_store.recalculate_buffer_diffs(buffers, cx)
3888 }))
3889 }
3890 })
3891 .ok()
3892 .flatten();
3893
3894 if let Some(task) = task {
3895 task.await;
3896 } else {
3897 break;
3898 }
3899 }
3900 })
3901 }
3902
3903 pub fn set_language_for_buffer(
3904 &mut self,
3905 buffer: &Entity<Buffer>,
3906 new_language: Arc<Language>,
3907 cx: &mut Context<Self>,
3908 ) {
3909 self.lsp_store.update(cx, |lsp_store, cx| {
3910 lsp_store.set_language_for_buffer(buffer, new_language, cx)
3911 })
3912 }
3913
3914 pub fn restart_language_servers_for_buffers(
3915 &mut self,
3916 buffers: Vec<Entity<Buffer>>,
3917 only_restart_servers: HashSet<LanguageServerSelector>,
3918 cx: &mut Context<Self>,
3919 ) {
3920 self.lsp_store.update(cx, |lsp_store, cx| {
3921 lsp_store.restart_language_servers_for_buffers(buffers, only_restart_servers, cx)
3922 })
3923 }
3924
3925 pub fn stop_language_servers_for_buffers(
3926 &mut self,
3927 buffers: Vec<Entity<Buffer>>,
3928 also_restart_servers: HashSet<LanguageServerSelector>,
3929 cx: &mut Context<Self>,
3930 ) {
3931 self.lsp_store
3932 .update(cx, |lsp_store, cx| {
3933 lsp_store.stop_language_servers_for_buffers(buffers, also_restart_servers, cx)
3934 })
3935 .detach_and_log_err(cx);
3936 }
3937
3938 pub fn cancel_language_server_work_for_buffers(
3939 &mut self,
3940 buffers: impl IntoIterator<Item = Entity<Buffer>>,
3941 cx: &mut Context<Self>,
3942 ) {
3943 self.lsp_store.update(cx, |lsp_store, cx| {
3944 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3945 })
3946 }
3947
3948 pub fn cancel_language_server_work(
3949 &mut self,
3950 server_id: LanguageServerId,
3951 token_to_cancel: Option<ProgressToken>,
3952 cx: &mut Context<Self>,
3953 ) {
3954 self.lsp_store.update(cx, |lsp_store, cx| {
3955 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3956 })
3957 }
3958
3959 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3960 self.buffer_ordered_messages_tx
3961 .unbounded_send(message)
3962 .map_err(|e| anyhow!(e))
3963 }
3964
3965 pub fn available_toolchains(
3966 &self,
3967 path: ProjectPath,
3968 language_name: LanguageName,
3969 cx: &App,
3970 ) -> Task<Option<Toolchains>> {
3971 if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3972 cx.spawn(async move |cx| {
3973 toolchain_store
3974 .update(cx, |this, cx| this.list_toolchains(path, language_name, cx))
3975 .ok()?
3976 .await
3977 })
3978 } else {
3979 Task::ready(None)
3980 }
3981 }
3982
3983 pub async fn toolchain_metadata(
3984 languages: Arc<LanguageRegistry>,
3985 language_name: LanguageName,
3986 ) -> Option<ToolchainMetadata> {
3987 languages
3988 .language_for_name(language_name.as_ref())
3989 .await
3990 .ok()?
3991 .toolchain_lister()
3992 .map(|lister| lister.meta())
3993 }
3994
3995 pub fn add_toolchain(
3996 &self,
3997 toolchain: Toolchain,
3998 scope: ToolchainScope,
3999 cx: &mut Context<Self>,
4000 ) {
4001 maybe!({
4002 self.toolchain_store.as_ref()?.update(cx, |this, cx| {
4003 this.add_toolchain(toolchain, scope, cx);
4004 });
4005 Some(())
4006 });
4007 }
4008
4009 pub fn remove_toolchain(
4010 &self,
4011 toolchain: Toolchain,
4012 scope: ToolchainScope,
4013 cx: &mut Context<Self>,
4014 ) {
4015 maybe!({
4016 self.toolchain_store.as_ref()?.update(cx, |this, cx| {
4017 this.remove_toolchain(toolchain, scope, cx);
4018 });
4019 Some(())
4020 });
4021 }
4022
4023 pub fn user_toolchains(
4024 &self,
4025 cx: &App,
4026 ) -> Option<BTreeMap<ToolchainScope, IndexSet<Toolchain>>> {
4027 Some(self.toolchain_store.as_ref()?.read(cx).user_toolchains())
4028 }
4029
4030 pub fn resolve_toolchain(
4031 &self,
4032 path: PathBuf,
4033 language_name: LanguageName,
4034 cx: &App,
4035 ) -> Task<Result<Toolchain>> {
4036 if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
4037 cx.spawn(async move |cx| {
4038 toolchain_store
4039 .update(cx, |this, cx| {
4040 this.resolve_toolchain(path, language_name, cx)
4041 })?
4042 .await
4043 })
4044 } else {
4045 Task::ready(Err(anyhow!("This project does not support toolchains")))
4046 }
4047 }
4048
4049 pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
4050 self.toolchain_store.clone()
4051 }
4052 pub fn activate_toolchain(
4053 &self,
4054 path: ProjectPath,
4055 toolchain: Toolchain,
4056 cx: &mut App,
4057 ) -> Task<Option<()>> {
4058 let Some(toolchain_store) = self.toolchain_store.clone() else {
4059 return Task::ready(None);
4060 };
4061 toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
4062 }
4063 pub fn active_toolchain(
4064 &self,
4065 path: ProjectPath,
4066 language_name: LanguageName,
4067 cx: &App,
4068 ) -> Task<Option<Toolchain>> {
4069 let Some(toolchain_store) = self.toolchain_store.clone() else {
4070 return Task::ready(None);
4071 };
4072 toolchain_store
4073 .read(cx)
4074 .active_toolchain(path, language_name, cx)
4075 }
4076 pub fn language_server_statuses<'a>(
4077 &'a self,
4078 cx: &'a App,
4079 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
4080 self.lsp_store.read(cx).language_server_statuses()
4081 }
4082
4083 pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
4084 self.lsp_store.read(cx).last_formatting_failure()
4085 }
4086
4087 pub fn reset_last_formatting_failure(&self, cx: &mut App) {
4088 self.lsp_store
4089 .update(cx, |store, _| store.reset_last_formatting_failure());
4090 }
4091
4092 pub fn reload_buffers(
4093 &self,
4094 buffers: HashSet<Entity<Buffer>>,
4095 push_to_history: bool,
4096 cx: &mut Context<Self>,
4097 ) -> Task<Result<ProjectTransaction>> {
4098 self.buffer_store.update(cx, |buffer_store, cx| {
4099 buffer_store.reload_buffers(buffers, push_to_history, cx)
4100 })
4101 }
4102
4103 pub fn reload_images(
4104 &self,
4105 images: HashSet<Entity<ImageItem>>,
4106 cx: &mut Context<Self>,
4107 ) -> Task<Result<()>> {
4108 self.image_store
4109 .update(cx, |image_store, cx| image_store.reload_images(images, cx))
4110 }
4111
4112 pub fn format(
4113 &mut self,
4114 buffers: HashSet<Entity<Buffer>>,
4115 target: LspFormatTarget,
4116 push_to_history: bool,
4117 trigger: lsp_store::FormatTrigger,
4118 cx: &mut Context<Project>,
4119 ) -> Task<anyhow::Result<ProjectTransaction>> {
4120 self.lsp_store.update(cx, |lsp_store, cx| {
4121 lsp_store.format(buffers, target, push_to_history, trigger, cx)
4122 })
4123 }
4124
4125 pub fn definitions<T: ToPointUtf16>(
4126 &mut self,
4127 buffer: &Entity<Buffer>,
4128 position: T,
4129 cx: &mut Context<Self>,
4130 ) -> Task<Result<Option<Vec<LocationLink>>>> {
4131 let position = position.to_point_utf16(buffer.read(cx));
4132 let guard = self.retain_remotely_created_models(cx);
4133 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4134 lsp_store.definitions(buffer, position, cx)
4135 });
4136 cx.background_spawn(async move {
4137 let result = task.await;
4138 drop(guard);
4139 result
4140 })
4141 }
4142
4143 pub fn declarations<T: ToPointUtf16>(
4144 &mut self,
4145 buffer: &Entity<Buffer>,
4146 position: T,
4147 cx: &mut Context<Self>,
4148 ) -> Task<Result<Option<Vec<LocationLink>>>> {
4149 let position = position.to_point_utf16(buffer.read(cx));
4150 let guard = self.retain_remotely_created_models(cx);
4151 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4152 lsp_store.declarations(buffer, position, cx)
4153 });
4154 cx.background_spawn(async move {
4155 let result = task.await;
4156 drop(guard);
4157 result
4158 })
4159 }
4160
4161 pub fn type_definitions<T: ToPointUtf16>(
4162 &mut self,
4163 buffer: &Entity<Buffer>,
4164 position: T,
4165 cx: &mut Context<Self>,
4166 ) -> Task<Result<Option<Vec<LocationLink>>>> {
4167 let position = position.to_point_utf16(buffer.read(cx));
4168 let guard = self.retain_remotely_created_models(cx);
4169 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4170 lsp_store.type_definitions(buffer, position, cx)
4171 });
4172 cx.background_spawn(async move {
4173 let result = task.await;
4174 drop(guard);
4175 result
4176 })
4177 }
4178
4179 pub fn implementations<T: ToPointUtf16>(
4180 &mut self,
4181 buffer: &Entity<Buffer>,
4182 position: T,
4183 cx: &mut Context<Self>,
4184 ) -> Task<Result<Option<Vec<LocationLink>>>> {
4185 let position = position.to_point_utf16(buffer.read(cx));
4186 let guard = self.retain_remotely_created_models(cx);
4187 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4188 lsp_store.implementations(buffer, position, cx)
4189 });
4190 cx.background_spawn(async move {
4191 let result = task.await;
4192 drop(guard);
4193 result
4194 })
4195 }
4196
4197 pub fn references<T: ToPointUtf16>(
4198 &mut self,
4199 buffer: &Entity<Buffer>,
4200 position: T,
4201 cx: &mut Context<Self>,
4202 ) -> Task<Result<Option<Vec<Location>>>> {
4203 let position = position.to_point_utf16(buffer.read(cx));
4204 let guard = self.retain_remotely_created_models(cx);
4205 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4206 lsp_store.references(buffer, position, cx)
4207 });
4208 cx.background_spawn(async move {
4209 let result = task.await;
4210 drop(guard);
4211 result
4212 })
4213 }
4214
4215 pub fn document_highlights<T: ToPointUtf16>(
4216 &mut self,
4217 buffer: &Entity<Buffer>,
4218 position: T,
4219 cx: &mut Context<Self>,
4220 ) -> Task<Result<Vec<DocumentHighlight>>> {
4221 let position = position.to_point_utf16(buffer.read(cx));
4222 self.request_lsp(
4223 buffer.clone(),
4224 LanguageServerToQuery::FirstCapable,
4225 GetDocumentHighlights { position },
4226 cx,
4227 )
4228 }
4229
4230 pub fn document_symbols(
4231 &mut self,
4232 buffer: &Entity<Buffer>,
4233 cx: &mut Context<Self>,
4234 ) -> Task<Result<Vec<DocumentSymbol>>> {
4235 self.request_lsp(
4236 buffer.clone(),
4237 LanguageServerToQuery::FirstCapable,
4238 GetDocumentSymbols,
4239 cx,
4240 )
4241 }
4242
4243 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
4244 self.lsp_store
4245 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
4246 }
4247
4248 pub fn open_buffer_for_symbol(
4249 &mut self,
4250 symbol: &Symbol,
4251 cx: &mut Context<Self>,
4252 ) -> Task<Result<Entity<Buffer>>> {
4253 self.lsp_store.update(cx, |lsp_store, cx| {
4254 lsp_store.open_buffer_for_symbol(symbol, cx)
4255 })
4256 }
4257
4258 pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
4259 let guard = self.retain_remotely_created_models(cx);
4260 let Some(remote) = self.remote_client.as_ref() else {
4261 return Task::ready(Err(anyhow!("not an ssh project")));
4262 };
4263
4264 let proto_client = remote.read(cx).proto_client();
4265
4266 cx.spawn(async move |project, cx| {
4267 let buffer = proto_client
4268 .request(proto::OpenServerSettings {
4269 project_id: REMOTE_SERVER_PROJECT_ID,
4270 })
4271 .await?;
4272
4273 let buffer = project
4274 .update(cx, |project, cx| {
4275 project.buffer_store.update(cx, |buffer_store, cx| {
4276 anyhow::Ok(
4277 buffer_store
4278 .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
4279 )
4280 })
4281 })??
4282 .await;
4283
4284 drop(guard);
4285 buffer
4286 })
4287 }
4288
4289 pub fn open_local_buffer_via_lsp(
4290 &mut self,
4291 abs_path: lsp::Uri,
4292 language_server_id: LanguageServerId,
4293 cx: &mut Context<Self>,
4294 ) -> Task<Result<Entity<Buffer>>> {
4295 self.lsp_store.update(cx, |lsp_store, cx| {
4296 lsp_store.open_local_buffer_via_lsp(abs_path, language_server_id, cx)
4297 })
4298 }
4299
4300 pub fn hover<T: ToPointUtf16>(
4301 &self,
4302 buffer: &Entity<Buffer>,
4303 position: T,
4304 cx: &mut Context<Self>,
4305 ) -> Task<Option<Vec<Hover>>> {
4306 let position = position.to_point_utf16(buffer.read(cx));
4307 self.lsp_store
4308 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
4309 }
4310
4311 pub fn linked_edits(
4312 &self,
4313 buffer: &Entity<Buffer>,
4314 position: Anchor,
4315 cx: &mut Context<Self>,
4316 ) -> Task<Result<Vec<Range<Anchor>>>> {
4317 self.lsp_store.update(cx, |lsp_store, cx| {
4318 lsp_store.linked_edits(buffer, position, cx)
4319 })
4320 }
4321
4322 pub fn completions<T: ToOffset + ToPointUtf16>(
4323 &self,
4324 buffer: &Entity<Buffer>,
4325 position: T,
4326 context: CompletionContext,
4327 cx: &mut Context<Self>,
4328 ) -> Task<Result<Vec<CompletionResponse>>> {
4329 let position = position.to_point_utf16(buffer.read(cx));
4330 self.lsp_store.update(cx, |lsp_store, cx| {
4331 lsp_store.completions(buffer, position, context, cx)
4332 })
4333 }
4334
4335 pub fn code_actions<T: Clone + ToOffset>(
4336 &mut self,
4337 buffer_handle: &Entity<Buffer>,
4338 range: Range<T>,
4339 kinds: Option<Vec<CodeActionKind>>,
4340 cx: &mut Context<Self>,
4341 ) -> Task<Result<Option<Vec<CodeAction>>>> {
4342 let buffer = buffer_handle.read(cx);
4343 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4344 self.lsp_store.update(cx, |lsp_store, cx| {
4345 lsp_store.code_actions(buffer_handle, range, kinds, cx)
4346 })
4347 }
4348
4349 pub fn code_lens_actions<T: Clone + ToOffset>(
4350 &mut self,
4351 buffer: &Entity<Buffer>,
4352 range: Range<T>,
4353 cx: &mut Context<Self>,
4354 ) -> Task<Result<Option<Vec<CodeAction>>>> {
4355 let snapshot = buffer.read(cx).snapshot();
4356 let range = range.to_point(&snapshot);
4357 let range_start = snapshot.anchor_before(range.start);
4358 let range_end = if range.start == range.end {
4359 range_start
4360 } else {
4361 snapshot.anchor_after(range.end)
4362 };
4363 let range = range_start..range_end;
4364 let code_lens_actions = self
4365 .lsp_store
4366 .update(cx, |lsp_store, cx| lsp_store.code_lens_actions(buffer, cx));
4367
4368 cx.background_spawn(async move {
4369 let mut code_lens_actions = code_lens_actions
4370 .await
4371 .map_err(|e| anyhow!("code lens fetch failed: {e:#}"))?;
4372 if let Some(code_lens_actions) = &mut code_lens_actions {
4373 code_lens_actions.retain(|code_lens_action| {
4374 range
4375 .start
4376 .cmp(&code_lens_action.range.start, &snapshot)
4377 .is_ge()
4378 && range
4379 .end
4380 .cmp(&code_lens_action.range.end, &snapshot)
4381 .is_le()
4382 });
4383 }
4384 Ok(code_lens_actions)
4385 })
4386 }
4387
4388 pub fn apply_code_action(
4389 &self,
4390 buffer_handle: Entity<Buffer>,
4391 action: CodeAction,
4392 push_to_history: bool,
4393 cx: &mut Context<Self>,
4394 ) -> Task<Result<ProjectTransaction>> {
4395 self.lsp_store.update(cx, |lsp_store, cx| {
4396 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
4397 })
4398 }
4399
4400 pub fn apply_code_action_kind(
4401 &self,
4402 buffers: HashSet<Entity<Buffer>>,
4403 kind: CodeActionKind,
4404 push_to_history: bool,
4405 cx: &mut Context<Self>,
4406 ) -> Task<Result<ProjectTransaction>> {
4407 self.lsp_store.update(cx, |lsp_store, cx| {
4408 lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
4409 })
4410 }
4411
4412 pub fn prepare_rename<T: ToPointUtf16>(
4413 &mut self,
4414 buffer: Entity<Buffer>,
4415 position: T,
4416 cx: &mut Context<Self>,
4417 ) -> Task<Result<PrepareRenameResponse>> {
4418 let position = position.to_point_utf16(buffer.read(cx));
4419 self.request_lsp(
4420 buffer,
4421 LanguageServerToQuery::FirstCapable,
4422 PrepareRename { position },
4423 cx,
4424 )
4425 }
4426
4427 pub fn perform_rename<T: ToPointUtf16>(
4428 &mut self,
4429 buffer: Entity<Buffer>,
4430 position: T,
4431 new_name: String,
4432 cx: &mut Context<Self>,
4433 ) -> Task<Result<ProjectTransaction>> {
4434 let push_to_history = true;
4435 let position = position.to_point_utf16(buffer.read(cx));
4436 self.request_lsp(
4437 buffer,
4438 LanguageServerToQuery::FirstCapable,
4439 PerformRename {
4440 position,
4441 new_name,
4442 push_to_history,
4443 },
4444 cx,
4445 )
4446 }
4447
4448 pub fn on_type_format<T: ToPointUtf16>(
4449 &mut self,
4450 buffer: Entity<Buffer>,
4451 position: T,
4452 trigger: String,
4453 push_to_history: bool,
4454 cx: &mut Context<Self>,
4455 ) -> Task<Result<Option<Transaction>>> {
4456 self.lsp_store.update(cx, |lsp_store, cx| {
4457 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
4458 })
4459 }
4460
4461 pub fn inline_values(
4462 &mut self,
4463 session: Entity<Session>,
4464 active_stack_frame: ActiveStackFrame,
4465 buffer_handle: Entity<Buffer>,
4466 range: Range<text::Anchor>,
4467 cx: &mut Context<Self>,
4468 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
4469 let snapshot = buffer_handle.read(cx).snapshot();
4470
4471 let captures =
4472 snapshot.debug_variables_query(Anchor::min_for_buffer(snapshot.remote_id())..range.end);
4473
4474 let row = snapshot
4475 .summary_for_anchor::<text::PointUtf16>(&range.end)
4476 .row as usize;
4477
4478 let inline_value_locations = provide_inline_values(captures, &snapshot, row);
4479
4480 let stack_frame_id = active_stack_frame.stack_frame_id;
4481 cx.spawn(async move |this, cx| {
4482 this.update(cx, |project, cx| {
4483 project.dap_store().update(cx, |dap_store, cx| {
4484 dap_store.resolve_inline_value_locations(
4485 session,
4486 stack_frame_id,
4487 buffer_handle,
4488 inline_value_locations,
4489 cx,
4490 )
4491 })
4492 })?
4493 .await
4494 })
4495 }
4496
4497 fn search_impl(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> SearchResultsHandle {
4498 let client: Option<(AnyProtoClient, _)> = if let Some(ssh_client) = &self.remote_client {
4499 Some((ssh_client.read(cx).proto_client(), 0))
4500 } else if let Some(remote_id) = self.remote_id() {
4501 self.is_local()
4502 .not()
4503 .then(|| (self.collab_client.clone().into(), remote_id))
4504 } else {
4505 None
4506 };
4507 let searcher = if query.is_opened_only() {
4508 project_search::Search::open_buffers_only(
4509 self.buffer_store.clone(),
4510 self.worktree_store.clone(),
4511 project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4512 )
4513 } else {
4514 match client {
4515 Some((client, remote_id)) => project_search::Search::remote(
4516 self.buffer_store.clone(),
4517 self.worktree_store.clone(),
4518 project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4519 (client, remote_id, self.remotely_created_models.clone()),
4520 ),
4521 None => project_search::Search::local(
4522 self.fs.clone(),
4523 self.buffer_store.clone(),
4524 self.worktree_store.clone(),
4525 project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4526 cx,
4527 ),
4528 }
4529 };
4530 searcher.into_handle(query, cx)
4531 }
4532
4533 pub fn search(
4534 &mut self,
4535 query: SearchQuery,
4536 cx: &mut Context<Self>,
4537 ) -> SearchResults<SearchResult> {
4538 self.search_impl(query, cx).results(cx)
4539 }
4540
4541 pub fn request_lsp<R: LspCommand>(
4542 &mut self,
4543 buffer_handle: Entity<Buffer>,
4544 server: LanguageServerToQuery,
4545 request: R,
4546 cx: &mut Context<Self>,
4547 ) -> Task<Result<R::Response>>
4548 where
4549 <R::LspRequest as lsp::request::Request>::Result: Send,
4550 <R::LspRequest as lsp::request::Request>::Params: Send,
4551 {
4552 let guard = self.retain_remotely_created_models(cx);
4553 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4554 lsp_store.request_lsp(buffer_handle, server, request, cx)
4555 });
4556 cx.background_spawn(async move {
4557 let result = task.await;
4558 drop(guard);
4559 result
4560 })
4561 }
4562
4563 /// Move a worktree to a new position in the worktree order.
4564 ///
4565 /// The worktree will moved to the opposite side of the destination worktree.
4566 ///
4567 /// # Example
4568 ///
4569 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4570 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4571 ///
4572 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4573 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4574 ///
4575 /// # Errors
4576 ///
4577 /// An error will be returned if the worktree or destination worktree are not found.
4578 pub fn move_worktree(
4579 &mut self,
4580 source: WorktreeId,
4581 destination: WorktreeId,
4582 cx: &mut Context<Self>,
4583 ) -> Result<()> {
4584 self.worktree_store.update(cx, |worktree_store, cx| {
4585 worktree_store.move_worktree(source, destination, cx)
4586 })
4587 }
4588
4589 /// Attempts to convert the input path to a WSL path if this is a wsl remote project and the input path is a host windows path.
4590 pub fn try_windows_path_to_wsl(
4591 &self,
4592 abs_path: &Path,
4593 cx: &App,
4594 ) -> impl Future<Output = Result<PathBuf>> + use<> {
4595 let fut = if cfg!(windows)
4596 && let (
4597 ProjectClientState::Local | ProjectClientState::Shared { .. },
4598 Some(remote_client),
4599 ) = (&self.client_state, &self.remote_client)
4600 && let RemoteConnectionOptions::Wsl(wsl) = remote_client.read(cx).connection_options()
4601 {
4602 Either::Left(wsl.abs_windows_path_to_wsl_path(abs_path))
4603 } else {
4604 Either::Right(abs_path.to_owned())
4605 };
4606 async move {
4607 match fut {
4608 Either::Left(fut) => fut.await.map(Into::into),
4609 Either::Right(path) => Ok(path),
4610 }
4611 }
4612 }
4613
4614 pub fn find_or_create_worktree(
4615 &mut self,
4616 abs_path: impl AsRef<Path>,
4617 visible: bool,
4618 cx: &mut Context<Self>,
4619 ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
4620 self.worktree_store.update(cx, |worktree_store, cx| {
4621 worktree_store.find_or_create_worktree(abs_path, visible, cx)
4622 })
4623 }
4624
4625 pub fn find_worktree(
4626 &self,
4627 abs_path: &Path,
4628 cx: &App,
4629 ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
4630 self.worktree_store.read(cx).find_worktree(abs_path, cx)
4631 }
4632
4633 pub fn is_shared(&self) -> bool {
4634 match &self.client_state {
4635 ProjectClientState::Shared { .. } => true,
4636 ProjectClientState::Local => false,
4637 ProjectClientState::Collab { .. } => true,
4638 }
4639 }
4640
4641 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4642 pub fn resolve_path_in_buffer(
4643 &self,
4644 path: &str,
4645 buffer: &Entity<Buffer>,
4646 cx: &mut Context<Self>,
4647 ) -> Task<Option<ResolvedPath>> {
4648 if util::paths::is_absolute(path, self.path_style(cx)) || path.starts_with("~") {
4649 self.resolve_abs_path(path, cx)
4650 } else {
4651 self.resolve_path_in_worktrees(path, buffer, cx)
4652 }
4653 }
4654
4655 pub fn resolve_abs_file_path(
4656 &self,
4657 path: &str,
4658 cx: &mut Context<Self>,
4659 ) -> Task<Option<ResolvedPath>> {
4660 let resolve_task = self.resolve_abs_path(path, cx);
4661 cx.background_spawn(async move {
4662 let resolved_path = resolve_task.await;
4663 resolved_path.filter(|path| path.is_file())
4664 })
4665 }
4666
4667 pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4668 if self.is_local() {
4669 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4670 let fs = self.fs.clone();
4671 cx.background_spawn(async move {
4672 let metadata = fs.metadata(&expanded).await.ok().flatten();
4673
4674 metadata.map(|metadata| ResolvedPath::AbsPath {
4675 path: expanded.to_string_lossy().into_owned(),
4676 is_dir: metadata.is_dir,
4677 })
4678 })
4679 } else if let Some(ssh_client) = self.remote_client.as_ref() {
4680 let request = ssh_client
4681 .read(cx)
4682 .proto_client()
4683 .request(proto::GetPathMetadata {
4684 project_id: REMOTE_SERVER_PROJECT_ID,
4685 path: path.into(),
4686 });
4687 cx.background_spawn(async move {
4688 let response = request.await.log_err()?;
4689 if response.exists {
4690 Some(ResolvedPath::AbsPath {
4691 path: response.path,
4692 is_dir: response.is_dir,
4693 })
4694 } else {
4695 None
4696 }
4697 })
4698 } else {
4699 Task::ready(None)
4700 }
4701 }
4702
4703 fn resolve_path_in_worktrees(
4704 &self,
4705 path: &str,
4706 buffer: &Entity<Buffer>,
4707 cx: &mut Context<Self>,
4708 ) -> Task<Option<ResolvedPath>> {
4709 let mut candidates = vec![];
4710 let path_style = self.path_style(cx);
4711 if let Ok(path) = RelPath::new(path.as_ref(), path_style) {
4712 candidates.push(path.into_arc());
4713 }
4714
4715 if let Some(file) = buffer.read(cx).file()
4716 && let Some(dir) = file.path().parent()
4717 {
4718 if let Some(joined) = path_style.join(&*dir.display(path_style), path)
4719 && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
4720 {
4721 candidates.push(joined.into_arc());
4722 }
4723 }
4724
4725 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4726 let worktrees_with_ids: Vec<_> = self
4727 .worktrees(cx)
4728 .map(|worktree| {
4729 let id = worktree.read(cx).id();
4730 (worktree, id)
4731 })
4732 .collect();
4733
4734 cx.spawn(async move |_, cx| {
4735 if let Some(buffer_worktree_id) = buffer_worktree_id
4736 && let Some((worktree, _)) = worktrees_with_ids
4737 .iter()
4738 .find(|(_, id)| *id == buffer_worktree_id)
4739 {
4740 for candidate in candidates.iter() {
4741 if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4742 return Some(path);
4743 }
4744 }
4745 }
4746 for (worktree, id) in worktrees_with_ids {
4747 if Some(id) == buffer_worktree_id {
4748 continue;
4749 }
4750 for candidate in candidates.iter() {
4751 if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4752 return Some(path);
4753 }
4754 }
4755 }
4756 None
4757 })
4758 }
4759
4760 fn resolve_path_in_worktree(
4761 worktree: &Entity<Worktree>,
4762 path: &RelPath,
4763 cx: &mut AsyncApp,
4764 ) -> Option<ResolvedPath> {
4765 worktree.read_with(cx, |worktree, _| {
4766 worktree.entry_for_path(path).map(|entry| {
4767 let project_path = ProjectPath {
4768 worktree_id: worktree.id(),
4769 path: entry.path.clone(),
4770 };
4771 ResolvedPath::ProjectPath {
4772 project_path,
4773 is_dir: entry.is_dir(),
4774 }
4775 })
4776 })
4777 }
4778
4779 pub fn list_directory(
4780 &self,
4781 query: String,
4782 cx: &mut Context<Self>,
4783 ) -> Task<Result<Vec<DirectoryItem>>> {
4784 if self.is_local() {
4785 DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4786 } else if let Some(session) = self.remote_client.as_ref() {
4787 let request = proto::ListRemoteDirectory {
4788 dev_server_id: REMOTE_SERVER_PROJECT_ID,
4789 path: query,
4790 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4791 };
4792
4793 let response = session.read(cx).proto_client().request(request);
4794 cx.background_spawn(async move {
4795 let proto::ListRemoteDirectoryResponse {
4796 entries,
4797 entry_info,
4798 } = response.await?;
4799 Ok(entries
4800 .into_iter()
4801 .zip(entry_info)
4802 .map(|(entry, info)| DirectoryItem {
4803 path: PathBuf::from(entry),
4804 is_dir: info.is_dir,
4805 })
4806 .collect())
4807 })
4808 } else {
4809 Task::ready(Err(anyhow!("cannot list directory in remote project")))
4810 }
4811 }
4812
4813 pub fn create_worktree(
4814 &mut self,
4815 abs_path: impl AsRef<Path>,
4816 visible: bool,
4817 cx: &mut Context<Self>,
4818 ) -> Task<Result<Entity<Worktree>>> {
4819 self.worktree_store.update(cx, |worktree_store, cx| {
4820 worktree_store.create_worktree(abs_path, visible, cx)
4821 })
4822 }
4823
4824 /// Returns a task that resolves when the given worktree's `Entity` is
4825 /// fully dropped (all strong references released), not merely when
4826 /// `remove_worktree` is called. `remove_worktree` drops the store's
4827 /// reference and emits `WorktreeRemoved`, but other code may still
4828 /// hold a strong handle — the worktree isn't safe to delete from
4829 /// disk until every handle is gone.
4830 ///
4831 /// We use `observe_release` on the specific entity rather than
4832 /// listening for `WorktreeReleased` events because it's simpler at
4833 /// the call site (one awaitable task, no subscription / channel /
4834 /// ID filtering).
4835 pub fn wait_for_worktree_release(
4836 &mut self,
4837 worktree_id: WorktreeId,
4838 cx: &mut Context<Self>,
4839 ) -> Task<Result<()>> {
4840 let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {
4841 return Task::ready(Ok(()));
4842 };
4843
4844 let (released_tx, released_rx) = futures::channel::oneshot::channel();
4845 let released_tx = std::sync::Arc::new(Mutex::new(Some(released_tx)));
4846 let release_subscription =
4847 cx.observe_release(&worktree, move |_project, _released_worktree, _cx| {
4848 if let Some(released_tx) = released_tx.lock().take() {
4849 let _ = released_tx.send(());
4850 }
4851 });
4852
4853 cx.spawn(async move |_project, _cx| {
4854 let _release_subscription = release_subscription;
4855 released_rx
4856 .await
4857 .map_err(|_| anyhow!("worktree release observer dropped before release"))?;
4858 Ok(())
4859 })
4860 }
4861
4862 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4863 self.worktree_store.update(cx, |worktree_store, cx| {
4864 worktree_store.remove_worktree(id_to_remove, cx);
4865 });
4866 }
4867
4868 pub fn remove_worktree_for_main_worktree_path(
4869 &mut self,
4870 path: impl AsRef<Path>,
4871 cx: &mut Context<Self>,
4872 ) {
4873 let path = path.as_ref();
4874 self.worktree_store.update(cx, |worktree_store, cx| {
4875 if let Some(worktree) = worktree_store.worktree_for_main_worktree_path(path, cx) {
4876 worktree_store.remove_worktree(worktree.read(cx).id(), cx);
4877 }
4878 });
4879 }
4880
4881 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4882 self.worktree_store.update(cx, |worktree_store, cx| {
4883 worktree_store.add(worktree, cx);
4884 });
4885 }
4886
4887 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4888 let new_active_entry = entry.and_then(|project_path| {
4889 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4890 let entry = worktree.read(cx).entry_for_path(&project_path.path)?;
4891 Some(entry.id)
4892 });
4893 if new_active_entry != self.active_entry {
4894 self.active_entry = new_active_entry;
4895 self.lsp_store.update(cx, |lsp_store, _| {
4896 lsp_store.set_active_entry(new_active_entry);
4897 });
4898 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4899 }
4900 }
4901
4902 pub fn language_servers_running_disk_based_diagnostics<'a>(
4903 &'a self,
4904 cx: &'a App,
4905 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4906 self.lsp_store
4907 .read(cx)
4908 .language_servers_running_disk_based_diagnostics()
4909 }
4910
4911 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4912 self.lsp_store
4913 .read(cx)
4914 .diagnostic_summary(include_ignored, cx)
4915 }
4916
4917 /// Returns a summary of the diagnostics for the provided project path only.
4918 pub fn diagnostic_summary_for_path(&self, path: &ProjectPath, cx: &App) -> DiagnosticSummary {
4919 self.lsp_store
4920 .read(cx)
4921 .diagnostic_summary_for_path(path, cx)
4922 }
4923
4924 pub fn diagnostic_summaries<'a>(
4925 &'a self,
4926 include_ignored: bool,
4927 cx: &'a App,
4928 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4929 self.lsp_store
4930 .read(cx)
4931 .diagnostic_summaries(include_ignored, cx)
4932 }
4933
4934 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4935 self.active_entry
4936 }
4937
4938 pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
4939 self.worktree_store.read(cx).entry_for_path(path, cx)
4940 }
4941
4942 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4943 let worktree = self.worktree_for_entry(entry_id, cx)?;
4944 let worktree = worktree.read(cx);
4945 let worktree_id = worktree.id();
4946 let path = worktree.entry_for_id(entry_id)?.path.clone();
4947 Some(ProjectPath { worktree_id, path })
4948 }
4949
4950 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4951 Some(
4952 self.worktree_for_id(project_path.worktree_id, cx)?
4953 .read(cx)
4954 .absolutize(&project_path.path),
4955 )
4956 }
4957
4958 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4959 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4960 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4961 /// the first visible worktree that has an entry for that relative path.
4962 ///
4963 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4964 /// root name from paths.
4965 ///
4966 /// # Arguments
4967 ///
4968 /// * `path` - An absolute path, or a full path that starts with a worktree root name, or a
4969 /// relative path within a visible worktree.
4970 /// * `cx` - A reference to the `AppContext`.
4971 ///
4972 /// # Returns
4973 ///
4974 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4975 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4976 let path_style = self.path_style(cx);
4977 let path = path.as_ref();
4978 let worktree_store = self.worktree_store.read(cx);
4979
4980 if is_absolute(&path.to_string_lossy(), path_style) {
4981 for worktree in worktree_store.visible_worktrees(cx) {
4982 let worktree_abs_path = worktree.read(cx).abs_path();
4983
4984 if let Ok(relative_path) = path.strip_prefix(worktree_abs_path)
4985 && let Ok(path) = RelPath::new(relative_path, path_style)
4986 {
4987 return Some(ProjectPath {
4988 worktree_id: worktree.read(cx).id(),
4989 path: path.into_arc(),
4990 });
4991 }
4992 }
4993 } else {
4994 for worktree in worktree_store.visible_worktrees(cx) {
4995 let worktree = worktree.read(cx);
4996 if let Ok(rel_path) = RelPath::new(path, path_style) {
4997 if let Some(entry) = worktree.entry_for_path(&rel_path) {
4998 return Some(ProjectPath {
4999 worktree_id: worktree.id(),
5000 path: entry.path.clone(),
5001 });
5002 }
5003 }
5004 }
5005
5006 for worktree in worktree_store.visible_worktrees(cx) {
5007 let worktree_root_name = worktree.read(cx).root_name();
5008 if let Ok(relative_path) = path.strip_prefix(worktree_root_name.as_std_path())
5009 && let Ok(path) = RelPath::new(relative_path, path_style)
5010 {
5011 return Some(ProjectPath {
5012 worktree_id: worktree.read(cx).id(),
5013 path: path.into_arc(),
5014 });
5015 }
5016 }
5017 }
5018
5019 None
5020 }
5021
5022 /// If there's only one visible worktree, returns the given worktree-relative path with no prefix.
5023 ///
5024 /// Otherwise, returns the full path for the project path (obtained by prefixing the worktree-relative path with the name of the worktree).
5025 pub fn short_full_path_for_project_path(
5026 &self,
5027 project_path: &ProjectPath,
5028 cx: &App,
5029 ) -> Option<String> {
5030 let path_style = self.path_style(cx);
5031 if self.visible_worktrees(cx).take(2).count() < 2 {
5032 return Some(project_path.path.display(path_style).to_string());
5033 }
5034 self.worktree_for_id(project_path.worktree_id, cx)
5035 .map(|worktree| {
5036 let worktree_name = worktree.read(cx).root_name();
5037 worktree_name
5038 .join(&project_path.path)
5039 .display(path_style)
5040 .to_string()
5041 })
5042 }
5043
5044 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
5045 self.worktree_store
5046 .read(cx)
5047 .project_path_for_absolute_path(abs_path, cx)
5048 }
5049
5050 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
5051 Some(
5052 self.worktree_for_id(project_path.worktree_id, cx)?
5053 .read(cx)
5054 .abs_path()
5055 .to_path_buf(),
5056 )
5057 }
5058
5059 pub fn blame_buffer(
5060 &self,
5061 buffer: &Entity<Buffer>,
5062 version: Option<clock::Global>,
5063 cx: &mut App,
5064 ) -> Task<Result<Option<Blame>>> {
5065 self.git_store.update(cx, |git_store, cx| {
5066 git_store.blame_buffer(buffer, version, cx)
5067 })
5068 }
5069
5070 pub fn get_permalink_to_line(
5071 &self,
5072 buffer: &Entity<Buffer>,
5073 selection: Range<u32>,
5074 cx: &mut App,
5075 ) -> Task<Result<url::Url>> {
5076 self.git_store.update(cx, |git_store, cx| {
5077 git_store.get_permalink_to_line(buffer, selection, cx)
5078 })
5079 }
5080
5081 // RPC message handlers
5082
5083 async fn handle_unshare_project(
5084 this: Entity<Self>,
5085 _: TypedEnvelope<proto::UnshareProject>,
5086 mut cx: AsyncApp,
5087 ) -> Result<()> {
5088 this.update(&mut cx, |this, cx| {
5089 if this.is_local() || this.is_via_remote_server() {
5090 this.unshare(cx)?;
5091 } else {
5092 this.disconnected_from_host(cx);
5093 }
5094 Ok(())
5095 })
5096 }
5097
5098 async fn handle_add_collaborator(
5099 this: Entity<Self>,
5100 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
5101 mut cx: AsyncApp,
5102 ) -> Result<()> {
5103 let collaborator = envelope
5104 .payload
5105 .collaborator
5106 .take()
5107 .context("empty collaborator")?;
5108
5109 let collaborator = Collaborator::from_proto(collaborator)?;
5110 this.update(&mut cx, |this, cx| {
5111 this.buffer_store.update(cx, |buffer_store, _| {
5112 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
5113 });
5114 this.breakpoint_store.read(cx).broadcast();
5115 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
5116 this.collaborators
5117 .insert(collaborator.peer_id, collaborator);
5118 });
5119
5120 Ok(())
5121 }
5122
5123 async fn handle_update_project_collaborator(
5124 this: Entity<Self>,
5125 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
5126 mut cx: AsyncApp,
5127 ) -> Result<()> {
5128 let old_peer_id = envelope
5129 .payload
5130 .old_peer_id
5131 .context("missing old peer id")?;
5132 let new_peer_id = envelope
5133 .payload
5134 .new_peer_id
5135 .context("missing new peer id")?;
5136 this.update(&mut cx, |this, cx| {
5137 let collaborator = this
5138 .collaborators
5139 .remove(&old_peer_id)
5140 .context("received UpdateProjectCollaborator for unknown peer")?;
5141 let is_host = collaborator.is_host;
5142 this.collaborators.insert(new_peer_id, collaborator);
5143
5144 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
5145 this.buffer_store.update(cx, |buffer_store, _| {
5146 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
5147 });
5148
5149 if is_host {
5150 this.buffer_store
5151 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
5152 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
5153 .unwrap();
5154 cx.emit(Event::HostReshared);
5155 }
5156
5157 cx.emit(Event::CollaboratorUpdated {
5158 old_peer_id,
5159 new_peer_id,
5160 });
5161 Ok(())
5162 })
5163 }
5164
5165 async fn handle_remove_collaborator(
5166 this: Entity<Self>,
5167 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
5168 mut cx: AsyncApp,
5169 ) -> Result<()> {
5170 this.update(&mut cx, |this, cx| {
5171 let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
5172 let replica_id = this
5173 .collaborators
5174 .remove(&peer_id)
5175 .with_context(|| format!("unknown peer {peer_id:?}"))?
5176 .replica_id;
5177 this.buffer_store.update(cx, |buffer_store, cx| {
5178 buffer_store.forget_shared_buffers_for(&peer_id);
5179 for buffer in buffer_store.buffers() {
5180 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
5181 }
5182 });
5183 this.git_store.update(cx, |git_store, _| {
5184 git_store.forget_shared_diffs_for(&peer_id);
5185 });
5186
5187 cx.emit(Event::CollaboratorLeft(peer_id));
5188 Ok(())
5189 })
5190 }
5191
5192 async fn handle_update_project(
5193 this: Entity<Self>,
5194 envelope: TypedEnvelope<proto::UpdateProject>,
5195 mut cx: AsyncApp,
5196 ) -> Result<()> {
5197 this.update(&mut cx, |this, cx| {
5198 // Don't handle messages that were sent before the response to us joining the project
5199 if envelope.message_id > this.join_project_response_message_id {
5200 cx.update_global::<SettingsStore, _>(|store, cx| {
5201 for worktree_metadata in &envelope.payload.worktrees {
5202 store
5203 .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
5204 .log_err();
5205 }
5206 });
5207
5208 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
5209 }
5210 Ok(())
5211 })
5212 }
5213
5214 async fn handle_toast(
5215 this: Entity<Self>,
5216 envelope: TypedEnvelope<proto::Toast>,
5217 mut cx: AsyncApp,
5218 ) -> Result<()> {
5219 this.update(&mut cx, |_, cx| {
5220 cx.emit(Event::Toast {
5221 notification_id: envelope.payload.notification_id.into(),
5222 message: envelope.payload.message,
5223 link: None,
5224 });
5225 Ok(())
5226 })
5227 }
5228
5229 async fn handle_language_server_prompt_request(
5230 this: Entity<Self>,
5231 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
5232 mut cx: AsyncApp,
5233 ) -> Result<proto::LanguageServerPromptResponse> {
5234 let (tx, rx) = smol::channel::bounded(1);
5235 let actions: Vec<_> = envelope
5236 .payload
5237 .actions
5238 .into_iter()
5239 .map(|action| MessageActionItem {
5240 title: action,
5241 properties: Default::default(),
5242 })
5243 .collect();
5244 this.update(&mut cx, |_, cx| {
5245 cx.emit(Event::LanguageServerPrompt(
5246 LanguageServerPromptRequest::new(
5247 proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
5248 envelope.payload.message,
5249 actions.clone(),
5250 envelope.payload.lsp_name,
5251 tx,
5252 ),
5253 ));
5254
5255 anyhow::Ok(())
5256 })?;
5257
5258 // We drop `this` to avoid holding a reference in this future for too
5259 // long.
5260 // If we keep the reference, we might not drop the `Project` early
5261 // enough when closing a window and it will only get releases on the
5262 // next `flush_effects()` call.
5263 drop(this);
5264
5265 let mut rx = pin!(rx);
5266 let answer = rx.next().await;
5267
5268 Ok(LanguageServerPromptResponse {
5269 action_response: answer.and_then(|answer| {
5270 actions
5271 .iter()
5272 .position(|action| *action == answer)
5273 .map(|index| index as u64)
5274 }),
5275 })
5276 }
5277
5278 async fn handle_hide_toast(
5279 this: Entity<Self>,
5280 envelope: TypedEnvelope<proto::HideToast>,
5281 mut cx: AsyncApp,
5282 ) -> Result<()> {
5283 this.update(&mut cx, |_, cx| {
5284 cx.emit(Event::HideToast {
5285 notification_id: envelope.payload.notification_id.into(),
5286 });
5287 Ok(())
5288 })
5289 }
5290
5291 // Collab sends UpdateWorktree protos as messages
5292 async fn handle_update_worktree(
5293 this: Entity<Self>,
5294 envelope: TypedEnvelope<proto::UpdateWorktree>,
5295 mut cx: AsyncApp,
5296 ) -> Result<()> {
5297 this.update(&mut cx, |project, cx| {
5298 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5299 if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
5300 worktree.update(cx, |worktree, _| {
5301 let worktree = worktree.as_remote_mut().unwrap();
5302 worktree.update_from_remote(envelope.payload);
5303 });
5304 }
5305 Ok(())
5306 })
5307 }
5308
5309 async fn handle_update_buffer_from_remote_server(
5310 this: Entity<Self>,
5311 envelope: TypedEnvelope<proto::UpdateBuffer>,
5312 cx: AsyncApp,
5313 ) -> Result<proto::Ack> {
5314 let buffer_store = this.read_with(&cx, |this, cx| {
5315 if let Some(remote_id) = this.remote_id() {
5316 let mut payload = envelope.payload.clone();
5317 payload.project_id = remote_id;
5318 cx.background_spawn(this.collab_client.request(payload))
5319 .detach_and_log_err(cx);
5320 }
5321 this.buffer_store.clone()
5322 });
5323 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
5324 }
5325
5326 async fn handle_trust_worktrees(
5327 this: Entity<Self>,
5328 envelope: TypedEnvelope<proto::TrustWorktrees>,
5329 mut cx: AsyncApp,
5330 ) -> Result<proto::Ack> {
5331 if this.read_with(&cx, |project, _| project.is_via_collab()) {
5332 return Ok(proto::Ack {});
5333 }
5334
5335 let trusted_worktrees = cx
5336 .update(|cx| TrustedWorktrees::try_get_global(cx))
5337 .context("missing trusted worktrees")?;
5338 trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
5339 trusted_worktrees.trust(
5340 &this.read(cx).worktree_store(),
5341 envelope
5342 .payload
5343 .trusted_paths
5344 .into_iter()
5345 .filter_map(|proto_path| PathTrust::from_proto(proto_path))
5346 .collect(),
5347 cx,
5348 );
5349 });
5350 Ok(proto::Ack {})
5351 }
5352
5353 async fn handle_restrict_worktrees(
5354 this: Entity<Self>,
5355 envelope: TypedEnvelope<proto::RestrictWorktrees>,
5356 mut cx: AsyncApp,
5357 ) -> Result<proto::Ack> {
5358 if this.read_with(&cx, |project, _| project.is_via_collab()) {
5359 return Ok(proto::Ack {});
5360 }
5361
5362 let trusted_worktrees = cx
5363 .update(|cx| TrustedWorktrees::try_get_global(cx))
5364 .context("missing trusted worktrees")?;
5365 trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
5366 let worktree_store = this.read(cx).worktree_store().downgrade();
5367 let restricted_paths = envelope
5368 .payload
5369 .worktree_ids
5370 .into_iter()
5371 .map(WorktreeId::from_proto)
5372 .map(PathTrust::Worktree)
5373 .collect::<HashSet<_>>();
5374 trusted_worktrees.restrict(worktree_store, restricted_paths, cx);
5375 });
5376 Ok(proto::Ack {})
5377 }
5378
5379 // Goes from host to client.
5380 async fn handle_find_search_candidates_chunk(
5381 this: Entity<Self>,
5382 envelope: TypedEnvelope<proto::FindSearchCandidatesChunk>,
5383 mut cx: AsyncApp,
5384 ) -> Result<proto::Ack> {
5385 let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
5386 BufferStore::handle_find_search_candidates_chunk(buffer_store, envelope, cx).await
5387 }
5388
5389 // Goes from client to host.
5390 async fn handle_find_search_candidates_cancel(
5391 this: Entity<Self>,
5392 envelope: TypedEnvelope<proto::FindSearchCandidatesCancelled>,
5393 mut cx: AsyncApp,
5394 ) -> Result<()> {
5395 let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
5396 BufferStore::handle_find_search_candidates_cancel(buffer_store, envelope, cx).await
5397 }
5398
5399 async fn handle_update_buffer(
5400 this: Entity<Self>,
5401 envelope: TypedEnvelope<proto::UpdateBuffer>,
5402 cx: AsyncApp,
5403 ) -> Result<proto::Ack> {
5404 let buffer_store = this.read_with(&cx, |this, cx| {
5405 if let Some(ssh) = &this.remote_client {
5406 let mut payload = envelope.payload.clone();
5407 payload.project_id = REMOTE_SERVER_PROJECT_ID;
5408 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
5409 .detach_and_log_err(cx);
5410 }
5411 this.buffer_store.clone()
5412 });
5413 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
5414 }
5415
5416 fn retain_remotely_created_models(
5417 &mut self,
5418 cx: &mut Context<Self>,
5419 ) -> RemotelyCreatedModelGuard {
5420 Self::retain_remotely_created_models_impl(
5421 &self.remotely_created_models,
5422 &self.buffer_store,
5423 &self.worktree_store,
5424 cx,
5425 )
5426 }
5427
5428 fn retain_remotely_created_models_impl(
5429 models: &Arc<Mutex<RemotelyCreatedModels>>,
5430 buffer_store: &Entity<BufferStore>,
5431 worktree_store: &Entity<WorktreeStore>,
5432 cx: &mut App,
5433 ) -> RemotelyCreatedModelGuard {
5434 {
5435 let mut remotely_create_models = models.lock();
5436 if remotely_create_models.retain_count == 0 {
5437 remotely_create_models.buffers = buffer_store.read(cx).buffers().collect();
5438 remotely_create_models.worktrees = worktree_store.read(cx).worktrees().collect();
5439 }
5440 remotely_create_models.retain_count += 1;
5441 }
5442 RemotelyCreatedModelGuard {
5443 remote_models: Arc::downgrade(&models),
5444 }
5445 }
5446
5447 async fn handle_create_buffer_for_peer(
5448 this: Entity<Self>,
5449 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5450 mut cx: AsyncApp,
5451 ) -> Result<()> {
5452 this.update(&mut cx, |this, cx| {
5453 this.buffer_store.update(cx, |buffer_store, cx| {
5454 buffer_store.handle_create_buffer_for_peer(
5455 envelope,
5456 this.replica_id(),
5457 this.capability(),
5458 cx,
5459 )
5460 })
5461 })
5462 }
5463
5464 async fn handle_toggle_lsp_logs(
5465 project: Entity<Self>,
5466 envelope: TypedEnvelope<proto::ToggleLspLogs>,
5467 mut cx: AsyncApp,
5468 ) -> Result<()> {
5469 let toggled_log_kind =
5470 match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
5471 .context("invalid log type")?
5472 {
5473 proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
5474 proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
5475 proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
5476 };
5477 project.update(&mut cx, |_, cx| {
5478 cx.emit(Event::ToggleLspLogs {
5479 server_id: LanguageServerId::from_proto(envelope.payload.server_id),
5480 enabled: envelope.payload.enabled,
5481 toggled_log_kind,
5482 })
5483 });
5484 Ok(())
5485 }
5486
5487 async fn handle_synchronize_buffers(
5488 this: Entity<Self>,
5489 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5490 mut cx: AsyncApp,
5491 ) -> Result<proto::SynchronizeBuffersResponse> {
5492 let response = this.update(&mut cx, |this, cx| {
5493 let client = this.collab_client.clone();
5494 this.buffer_store.update(cx, |this, cx| {
5495 this.handle_synchronize_buffers(envelope, cx, client)
5496 })
5497 })?;
5498
5499 Ok(response)
5500 }
5501
5502 // Goes from client to host.
5503 async fn handle_search_candidate_buffers(
5504 this: Entity<Self>,
5505 envelope: TypedEnvelope<proto::FindSearchCandidates>,
5506 mut cx: AsyncApp,
5507 ) -> Result<proto::Ack> {
5508 let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
5509 let message = envelope.payload;
5510 let project_id = message.project_id;
5511 let path_style = this.read_with(&cx, |this, cx| this.path_style(cx));
5512 let query =
5513 SearchQuery::from_proto(message.query.context("missing query field")?, path_style)?;
5514
5515 let handle = message.handle;
5516 let buffer_store = this.read_with(&cx, |this, _| this.buffer_store().clone());
5517 let client = this.read_with(&cx, |this, _| this.client());
5518 let task = cx.spawn(async move |cx| {
5519 let results = this.update(cx, |this, cx| {
5520 this.search_impl(query, cx).matching_buffers(cx)
5521 });
5522 let (batcher, batches) = project_search::AdaptiveBatcher::new(cx.background_executor());
5523 let mut new_matches = Box::pin(results.rx);
5524
5525 let sender_task = cx.background_executor().spawn({
5526 let client = client.clone();
5527 async move {
5528 let mut batches = std::pin::pin!(batches);
5529 while let Some(buffer_ids) = batches.next().await {
5530 client
5531 .request(proto::FindSearchCandidatesChunk {
5532 handle,
5533 peer_id: Some(peer_id),
5534 project_id,
5535 variant: Some(
5536 proto::find_search_candidates_chunk::Variant::Matches(
5537 proto::FindSearchCandidatesMatches { buffer_ids },
5538 ),
5539 ),
5540 })
5541 .await?;
5542 }
5543 anyhow::Ok(())
5544 }
5545 });
5546
5547 while let Some(buffer) = new_matches.next().await {
5548 let buffer_id = this.update(cx, |this, cx| {
5549 this.create_buffer_for_peer(&buffer, peer_id, cx).to_proto()
5550 });
5551 batcher.push(buffer_id).await;
5552 }
5553 batcher.flush().await;
5554
5555 sender_task.await?;
5556
5557 let _ = client
5558 .request(proto::FindSearchCandidatesChunk {
5559 handle,
5560 peer_id: Some(peer_id),
5561 project_id,
5562 variant: Some(proto::find_search_candidates_chunk::Variant::Done(
5563 proto::FindSearchCandidatesDone {},
5564 )),
5565 })
5566 .await?;
5567 anyhow::Ok(())
5568 });
5569 buffer_store.update(&mut cx, |this, _| {
5570 this.register_ongoing_project_search((peer_id, handle), task);
5571 });
5572
5573 Ok(proto::Ack {})
5574 }
5575
5576 async fn handle_open_buffer_by_id(
5577 this: Entity<Self>,
5578 envelope: TypedEnvelope<proto::OpenBufferById>,
5579 mut cx: AsyncApp,
5580 ) -> Result<proto::OpenBufferResponse> {
5581 let peer_id = envelope.original_sender_id()?;
5582 let buffer_id = BufferId::new(envelope.payload.id)?;
5583 let buffer = this
5584 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))
5585 .await?;
5586 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5587 }
5588
5589 async fn handle_open_buffer_by_path(
5590 this: Entity<Self>,
5591 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5592 mut cx: AsyncApp,
5593 ) -> Result<proto::OpenBufferResponse> {
5594 let peer_id = envelope.original_sender_id()?;
5595 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5596 let path = RelPath::from_proto(&envelope.payload.path)?;
5597 let open_buffer = this
5598 .update(&mut cx, |this, cx| {
5599 this.open_buffer(ProjectPath { worktree_id, path }, cx)
5600 })
5601 .await?;
5602 Project::respond_to_open_buffer_request(this, open_buffer, peer_id, &mut cx)
5603 }
5604
5605 async fn handle_open_new_buffer(
5606 this: Entity<Self>,
5607 envelope: TypedEnvelope<proto::OpenNewBuffer>,
5608 mut cx: AsyncApp,
5609 ) -> Result<proto::OpenBufferResponse> {
5610 let buffer = this
5611 .update(&mut cx, |this, cx| this.create_buffer(None, true, cx))
5612 .await?;
5613 let peer_id = envelope.original_sender_id()?;
5614
5615 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5616 }
5617
5618 fn respond_to_open_buffer_request(
5619 this: Entity<Self>,
5620 buffer: Entity<Buffer>,
5621 peer_id: proto::PeerId,
5622 cx: &mut AsyncApp,
5623 ) -> Result<proto::OpenBufferResponse> {
5624 this.update(cx, |this, cx| {
5625 let is_private = buffer
5626 .read(cx)
5627 .file()
5628 .map(|f| f.is_private())
5629 .unwrap_or_default();
5630 anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
5631 Ok(proto::OpenBufferResponse {
5632 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
5633 })
5634 })
5635 }
5636
5637 fn create_buffer_for_peer(
5638 &mut self,
5639 buffer: &Entity<Buffer>,
5640 peer_id: proto::PeerId,
5641 cx: &mut App,
5642 ) -> BufferId {
5643 self.buffer_store
5644 .update(cx, |buffer_store, cx| {
5645 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
5646 })
5647 .detach_and_log_err(cx);
5648 buffer.read(cx).remote_id()
5649 }
5650
5651 async fn handle_create_image_for_peer(
5652 this: Entity<Self>,
5653 envelope: TypedEnvelope<proto::CreateImageForPeer>,
5654 mut cx: AsyncApp,
5655 ) -> Result<()> {
5656 this.update(&mut cx, |this, cx| {
5657 this.image_store.update(cx, |image_store, cx| {
5658 image_store.handle_create_image_for_peer(envelope, cx)
5659 })
5660 })
5661 }
5662
5663 async fn handle_create_file_for_peer(
5664 this: Entity<Self>,
5665 envelope: TypedEnvelope<proto::CreateFileForPeer>,
5666 mut cx: AsyncApp,
5667 ) -> Result<()> {
5668 use proto::create_file_for_peer::Variant;
5669 log::debug!("handle_create_file_for_peer: received message");
5670
5671 let downloading_files: Arc<Mutex<HashMap<(WorktreeId, String), DownloadingFile>>> =
5672 this.update(&mut cx, |this, _| this.downloading_files.clone());
5673
5674 match &envelope.payload.variant {
5675 Some(Variant::State(state)) => {
5676 log::debug!(
5677 "handle_create_file_for_peer: got State: id={}, content_size={}",
5678 state.id,
5679 state.content_size
5680 );
5681
5682 // Extract worktree_id and path from the File field
5683 if let Some(ref file) = state.file {
5684 let worktree_id = WorktreeId::from_proto(file.worktree_id);
5685 let path = file.path.clone();
5686 let key = (worktree_id, path);
5687 log::debug!("handle_create_file_for_peer: looking up key={:?}", key);
5688
5689 let empty_file_destination: Option<PathBuf> = {
5690 let mut files = downloading_files.lock();
5691 log::trace!(
5692 "handle_create_file_for_peer: current downloading_files keys: {:?}",
5693 files.keys().collect::<Vec<_>>()
5694 );
5695
5696 if let Some(file_entry) = files.get_mut(&key) {
5697 file_entry.total_size = state.content_size;
5698 file_entry.file_id = Some(state.id);
5699 log::debug!(
5700 "handle_create_file_for_peer: updated file entry: total_size={}, file_id={}",
5701 state.content_size,
5702 state.id
5703 );
5704 } else {
5705 log::warn!(
5706 "handle_create_file_for_peer: key={:?} not found in downloading_files",
5707 key
5708 );
5709 }
5710
5711 if state.content_size == 0 {
5712 // No chunks will arrive for an empty file; write it now.
5713 files.remove(&key).map(|entry| entry.destination_path)
5714 } else {
5715 None
5716 }
5717 };
5718
5719 if let Some(destination) = empty_file_destination {
5720 log::debug!(
5721 "handle_create_file_for_peer: writing empty file to {:?}",
5722 destination
5723 );
5724 match smol::fs::write(&destination, &[] as &[u8]).await {
5725 Ok(_) => log::info!(
5726 "handle_create_file_for_peer: successfully wrote file to {:?}",
5727 destination
5728 ),
5729 Err(e) => log::error!(
5730 "handle_create_file_for_peer: failed to write empty file: {:?}",
5731 e
5732 ),
5733 }
5734 }
5735 } else {
5736 log::warn!("handle_create_file_for_peer: State has no file field");
5737 }
5738 }
5739 Some(Variant::Chunk(chunk)) => {
5740 log::debug!(
5741 "handle_create_file_for_peer: got Chunk: file_id={}, data_len={}",
5742 chunk.file_id,
5743 chunk.data.len()
5744 );
5745
5746 // Extract data while holding the lock, then release it before await
5747 let (key_to_remove, write_info): (
5748 Option<(WorktreeId, String)>,
5749 Option<(PathBuf, Vec<u8>)>,
5750 ) = {
5751 let mut files = downloading_files.lock();
5752 let mut found_key: Option<(WorktreeId, String)> = None;
5753 let mut write_data: Option<(PathBuf, Vec<u8>)> = None;
5754
5755 for (key, file_entry) in files.iter_mut() {
5756 if file_entry.file_id == Some(chunk.file_id) {
5757 file_entry.chunks.extend_from_slice(&chunk.data);
5758 log::debug!(
5759 "handle_create_file_for_peer: accumulated {} bytes, total_size={}",
5760 file_entry.chunks.len(),
5761 file_entry.total_size
5762 );
5763
5764 if file_entry.chunks.len() as u64 >= file_entry.total_size
5765 && file_entry.total_size > 0
5766 {
5767 let destination = file_entry.destination_path.clone();
5768 let content = std::mem::take(&mut file_entry.chunks);
5769 found_key = Some(key.clone());
5770 write_data = Some((destination, content));
5771 }
5772 break;
5773 }
5774 }
5775 (found_key, write_data)
5776 }; // MutexGuard is dropped here
5777
5778 // Perform the async write outside the lock
5779 if let Some((destination, content)) = write_info {
5780 log::debug!(
5781 "handle_create_file_for_peer: writing {} bytes to {:?}",
5782 content.len(),
5783 destination
5784 );
5785 match smol::fs::write(&destination, &content).await {
5786 Ok(_) => log::info!(
5787 "handle_create_file_for_peer: successfully wrote file to {:?}",
5788 destination
5789 ),
5790 Err(e) => log::error!(
5791 "handle_create_file_for_peer: failed to write file: {:?}",
5792 e
5793 ),
5794 }
5795 }
5796
5797 // Remove the completed entry
5798 if let Some(key) = key_to_remove {
5799 downloading_files.lock().remove(&key);
5800 log::debug!("handle_create_file_for_peer: removed completed download entry");
5801 }
5802 }
5803 None => {
5804 log::warn!("handle_create_file_for_peer: got None variant");
5805 }
5806 }
5807
5808 Ok(())
5809 }
5810
5811 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
5812 let project_id = match self.client_state {
5813 ProjectClientState::Collab {
5814 sharing_has_stopped,
5815 remote_id,
5816 ..
5817 } => {
5818 if sharing_has_stopped {
5819 return Task::ready(Err(anyhow!(
5820 "can't synchronize remote buffers on a readonly project"
5821 )));
5822 } else {
5823 remote_id
5824 }
5825 }
5826 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
5827 return Task::ready(Err(anyhow!(
5828 "can't synchronize remote buffers on a local project"
5829 )));
5830 }
5831 };
5832
5833 let client = self.collab_client.clone();
5834 cx.spawn(async move |this, cx| {
5835 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
5836 this.buffer_store.read(cx).buffer_version_info(cx)
5837 })?;
5838 let response = client
5839 .request(proto::SynchronizeBuffers {
5840 project_id,
5841 buffers,
5842 })
5843 .await?;
5844
5845 let send_updates_for_buffers = this.update(cx, |this, cx| {
5846 response
5847 .buffers
5848 .into_iter()
5849 .map(|buffer| {
5850 let client = client.clone();
5851 let buffer_id = match BufferId::new(buffer.id) {
5852 Ok(id) => id,
5853 Err(e) => {
5854 return Task::ready(Err(e));
5855 }
5856 };
5857 let remote_version = language::proto::deserialize_version(&buffer.version);
5858 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5859 let operations =
5860 buffer.read(cx).serialize_ops(Some(remote_version), cx);
5861 cx.background_spawn(async move {
5862 let operations = operations.await;
5863 for chunk in split_operations(operations) {
5864 client
5865 .request(proto::UpdateBuffer {
5866 project_id,
5867 buffer_id: buffer_id.into(),
5868 operations: chunk,
5869 })
5870 .await?;
5871 }
5872 anyhow::Ok(())
5873 })
5874 } else {
5875 Task::ready(Ok(()))
5876 }
5877 })
5878 .collect::<Vec<_>>()
5879 })?;
5880
5881 // Any incomplete buffers have open requests waiting. Request that the host sends
5882 // creates these buffers for us again to unblock any waiting futures.
5883 for id in incomplete_buffer_ids {
5884 cx.background_spawn(client.request(proto::OpenBufferById {
5885 project_id,
5886 id: id.into(),
5887 }))
5888 .detach();
5889 }
5890
5891 futures::future::join_all(send_updates_for_buffers)
5892 .await
5893 .into_iter()
5894 .collect()
5895 })
5896 }
5897
5898 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
5899 self.worktree_store.read(cx).worktree_metadata_protos(cx)
5900 }
5901
5902 /// Iterator of all open buffers that have unsaved changes
5903 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
5904 self.buffer_store.read(cx).buffers().filter_map(|buf| {
5905 let buf = buf.read(cx);
5906 if buf.is_dirty() {
5907 buf.project_path(cx)
5908 } else {
5909 None
5910 }
5911 })
5912 }
5913
5914 fn set_worktrees_from_proto(
5915 &mut self,
5916 worktrees: Vec<proto::WorktreeMetadata>,
5917 cx: &mut Context<Project>,
5918 ) -> Result<()> {
5919 self.worktree_store.update(cx, |worktree_store, cx| {
5920 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
5921 })
5922 }
5923
5924 fn set_collaborators_from_proto(
5925 &mut self,
5926 messages: Vec<proto::Collaborator>,
5927 cx: &mut Context<Self>,
5928 ) -> Result<()> {
5929 let mut collaborators = HashMap::default();
5930 for message in messages {
5931 let collaborator = Collaborator::from_proto(message)?;
5932 collaborators.insert(collaborator.peer_id, collaborator);
5933 }
5934 for old_peer_id in self.collaborators.keys() {
5935 if !collaborators.contains_key(old_peer_id) {
5936 cx.emit(Event::CollaboratorLeft(*old_peer_id));
5937 }
5938 }
5939 self.collaborators = collaborators;
5940 Ok(())
5941 }
5942
5943 pub fn supplementary_language_servers<'a>(
5944 &'a self,
5945 cx: &'a App,
5946 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
5947 self.lsp_store.read(cx).supplementary_language_servers()
5948 }
5949
5950 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
5951 let Some(language) = buffer.language().cloned() else {
5952 return false;
5953 };
5954 self.lsp_store.update(cx, |lsp_store, _| {
5955 let relevant_language_servers = lsp_store
5956 .languages
5957 .lsp_adapters(&language.name())
5958 .into_iter()
5959 .map(|lsp_adapter| lsp_adapter.name())
5960 .collect::<HashSet<_>>();
5961 lsp_store
5962 .language_server_statuses()
5963 .filter_map(|(server_id, server_status)| {
5964 relevant_language_servers
5965 .contains(&server_status.name)
5966 .then_some(server_id)
5967 })
5968 .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5969 .any(InlayHints::check_capabilities)
5970 })
5971 }
5972
5973 pub fn any_language_server_supports_semantic_tokens(
5974 &self,
5975 buffer: &Buffer,
5976 cx: &mut App,
5977 ) -> bool {
5978 let Some(language) = buffer.language().cloned() else {
5979 return false;
5980 };
5981 let lsp_store = self.lsp_store.read(cx);
5982 let relevant_language_servers = lsp_store
5983 .languages
5984 .lsp_adapters(&language.name())
5985 .into_iter()
5986 .map(|lsp_adapter| lsp_adapter.name())
5987 .collect::<HashSet<_>>();
5988 lsp_store
5989 .language_server_statuses()
5990 .filter_map(|(server_id, server_status)| {
5991 relevant_language_servers
5992 .contains(&server_status.name)
5993 .then_some(server_id)
5994 })
5995 .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5996 .any(|capabilities| capabilities.semantic_tokens_provider.is_some())
5997 }
5998
5999 pub fn language_server_id_for_name(
6000 &self,
6001 buffer: &Buffer,
6002 name: &LanguageServerName,
6003 cx: &App,
6004 ) -> Option<LanguageServerId> {
6005 let language = buffer.language()?;
6006 let relevant_language_servers = self
6007 .languages
6008 .lsp_adapters(&language.name())
6009 .into_iter()
6010 .map(|lsp_adapter| lsp_adapter.name())
6011 .collect::<HashSet<_>>();
6012 if !relevant_language_servers.contains(name) {
6013 return None;
6014 }
6015 self.language_server_statuses(cx)
6016 .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
6017 .find_map(|(server_id, server_status)| {
6018 if &server_status.name == name {
6019 Some(server_id)
6020 } else {
6021 None
6022 }
6023 })
6024 }
6025
6026 #[cfg(feature = "test-support")]
6027 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
6028 self.lsp_store.update(cx, |this, cx| {
6029 this.running_language_servers_for_local_buffer(buffer, cx)
6030 .next()
6031 .is_some()
6032 })
6033 }
6034
6035 pub fn git_init(
6036 &self,
6037 path: Arc<Path>,
6038 fallback_branch_name: String,
6039 cx: &App,
6040 ) -> Task<Result<()>> {
6041 self.git_store
6042 .read(cx)
6043 .git_init(path, fallback_branch_name, cx)
6044 }
6045
6046 pub fn buffer_store(&self) -> &Entity<BufferStore> {
6047 &self.buffer_store
6048 }
6049
6050 pub fn git_store(&self) -> &Entity<GitStore> {
6051 &self.git_store
6052 }
6053
6054 pub fn agent_server_store(&self) -> &Entity<AgentServerStore> {
6055 &self.agent_server_store
6056 }
6057
6058 #[cfg(feature = "test-support")]
6059 pub fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
6060 use futures::future::join_all;
6061 cx.spawn(async move |this, cx| {
6062 let scans_complete = this
6063 .read_with(cx, |this, cx| {
6064 this.worktrees(cx)
6065 .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
6066 .collect::<Vec<_>>()
6067 })
6068 .unwrap();
6069 join_all(scans_complete).await;
6070 let barriers = this
6071 .update(cx, |this, cx| {
6072 let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
6073 repos
6074 .into_iter()
6075 .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
6076 .collect::<Vec<_>>()
6077 })
6078 .unwrap();
6079 join_all(barriers).await;
6080 })
6081 }
6082
6083 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
6084 self.git_store.read(cx).active_repository()
6085 }
6086
6087 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
6088 self.git_store.read(cx).repositories()
6089 }
6090
6091 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
6092 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
6093 }
6094
6095 pub fn set_agent_location(
6096 &mut self,
6097 new_location: Option<AgentLocation>,
6098 cx: &mut Context<Self>,
6099 ) {
6100 if let Some(old_location) = self.agent_location.as_ref() {
6101 old_location
6102 .buffer
6103 .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
6104 .ok();
6105 }
6106
6107 if let Some(location) = new_location.as_ref() {
6108 location
6109 .buffer
6110 .update(cx, |buffer, cx| {
6111 buffer.set_agent_selections(
6112 Arc::from([language::Selection {
6113 id: 0,
6114 start: location.position,
6115 end: location.position,
6116 reversed: false,
6117 goal: language::SelectionGoal::None,
6118 }]),
6119 false,
6120 CursorShape::Hollow,
6121 cx,
6122 )
6123 })
6124 .ok();
6125 }
6126
6127 self.agent_location = new_location;
6128 cx.emit(Event::AgentLocationChanged);
6129 }
6130
6131 pub fn agent_location(&self) -> Option<AgentLocation> {
6132 self.agent_location.clone()
6133 }
6134
6135 pub fn path_style(&self, cx: &App) -> PathStyle {
6136 self.worktree_store.read(cx).path_style()
6137 }
6138
6139 pub fn contains_local_settings_file(
6140 &self,
6141 worktree_id: WorktreeId,
6142 rel_path: &RelPath,
6143 cx: &App,
6144 ) -> bool {
6145 self.worktree_for_id(worktree_id, cx)
6146 .map_or(false, |worktree| {
6147 worktree.read(cx).entry_for_path(rel_path).is_some()
6148 })
6149 }
6150
6151 pub fn worktree_paths(&self, cx: &App) -> WorktreePaths {
6152 self.worktree_store.read(cx).paths(cx)
6153 }
6154
6155 pub fn project_group_key(&self, cx: &App) -> ProjectGroupKey {
6156 ProjectGroupKey::from_project(self, cx)
6157 }
6158}
6159
6160/// Identifies a project group by a set of paths the workspaces in this group
6161/// have.
6162///
6163/// Paths are mapped to their main worktree path first so we can group
6164/// workspaces by main repos.
6165#[derive(PartialEq, Eq, Hash, Clone, Debug, Default)]
6166pub struct ProjectGroupKey {
6167 /// The paths of the main worktrees for this project group.
6168 paths: PathList,
6169 host: Option<RemoteConnectionOptions>,
6170}
6171
6172impl ProjectGroupKey {
6173 /// Creates a new `ProjectGroupKey` with the given path list.
6174 ///
6175 /// The path list should point to the git main worktree paths for a project.
6176 pub fn new(host: Option<RemoteConnectionOptions>, paths: PathList) -> Self {
6177 Self { paths, host }
6178 }
6179
6180 pub fn from_project(project: &Project, cx: &App) -> Self {
6181 let paths = project.worktree_paths(cx);
6182 let host = project.remote_connection_options(cx);
6183 Self {
6184 paths: paths.main_worktree_path_list().clone(),
6185 host,
6186 }
6187 }
6188
6189 pub fn from_worktree_paths(
6190 paths: &WorktreePaths,
6191 host: Option<RemoteConnectionOptions>,
6192 ) -> Self {
6193 Self {
6194 paths: paths.main_worktree_path_list().clone(),
6195 host,
6196 }
6197 }
6198
6199 pub fn path_list(&self) -> &PathList {
6200 &self.paths
6201 }
6202
6203 pub fn display_name(
6204 &self,
6205 path_detail_map: &std::collections::HashMap<PathBuf, usize>,
6206 ) -> SharedString {
6207 let mut names = Vec::with_capacity(self.paths.paths().len());
6208 for abs_path in self.paths.ordered_paths() {
6209 let detail = path_detail_map.get(abs_path).copied().unwrap_or(0);
6210 let suffix = path_suffix(abs_path, detail);
6211 if !suffix.is_empty() {
6212 names.push(suffix);
6213 }
6214 }
6215 if names.is_empty() {
6216 "Empty Workspace".into()
6217 } else {
6218 names.join(", ").into()
6219 }
6220 }
6221
6222 pub fn host(&self) -> Option<RemoteConnectionOptions> {
6223 self.host.clone()
6224 }
6225}
6226
6227pub fn path_suffix(path: &Path, detail: usize) -> String {
6228 let mut components: Vec<_> = path
6229 .components()
6230 .rev()
6231 .filter_map(|component| match component {
6232 std::path::Component::Normal(s) => Some(s.to_string_lossy()),
6233 _ => None,
6234 })
6235 .take(detail + 1)
6236 .collect();
6237 components.reverse();
6238 components.join("/")
6239}
6240
6241pub struct PathMatchCandidateSet {
6242 pub snapshot: Snapshot,
6243 pub include_ignored: bool,
6244 pub include_root_name: bool,
6245 pub candidates: Candidates,
6246}
6247
6248pub enum Candidates {
6249 /// Only consider directories.
6250 Directories,
6251 /// Only consider files.
6252 Files,
6253 /// Consider directories and files.
6254 Entries,
6255}
6256
6257impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6258 type Candidates = PathMatchCandidateSetIter<'a>;
6259
6260 fn id(&self) -> usize {
6261 self.snapshot.id().to_usize()
6262 }
6263
6264 fn len(&self) -> usize {
6265 match self.candidates {
6266 Candidates::Files => {
6267 if self.include_ignored {
6268 self.snapshot.file_count()
6269 } else {
6270 self.snapshot.visible_file_count()
6271 }
6272 }
6273
6274 Candidates::Directories => {
6275 if self.include_ignored {
6276 self.snapshot.dir_count()
6277 } else {
6278 self.snapshot.visible_dir_count()
6279 }
6280 }
6281
6282 Candidates::Entries => {
6283 if self.include_ignored {
6284 self.snapshot.entry_count()
6285 } else {
6286 self.snapshot.visible_entry_count()
6287 }
6288 }
6289 }
6290 }
6291
6292 fn prefix(&self) -> Arc<RelPath> {
6293 if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
6294 self.snapshot.root_name().into()
6295 } else {
6296 RelPath::empty().into()
6297 }
6298 }
6299
6300 fn root_is_file(&self) -> bool {
6301 self.snapshot.root_entry().is_some_and(|f| f.is_file())
6302 }
6303
6304 fn path_style(&self) -> PathStyle {
6305 self.snapshot.path_style()
6306 }
6307
6308 fn candidates(&'a self, start: usize) -> Self::Candidates {
6309 PathMatchCandidateSetIter {
6310 traversal: match self.candidates {
6311 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
6312 Candidates::Files => self.snapshot.files(self.include_ignored, start),
6313 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
6314 },
6315 }
6316 }
6317}
6318
6319pub struct PathMatchCandidateSetIter<'a> {
6320 traversal: Traversal<'a>,
6321}
6322
6323impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6324 type Item = fuzzy::PathMatchCandidate<'a>;
6325
6326 fn next(&mut self) -> Option<Self::Item> {
6327 self.traversal
6328 .next()
6329 .map(|entry| fuzzy::PathMatchCandidate {
6330 is_dir: entry.kind.is_dir(),
6331 path: &entry.path,
6332 char_bag: entry.char_bag,
6333 })
6334 }
6335}
6336
6337impl<'a> fuzzy_nucleo::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6338 type Candidates = PathMatchCandidateSetNucleoIter<'a>;
6339 fn id(&self) -> usize {
6340 self.snapshot.id().to_usize()
6341 }
6342 fn len(&self) -> usize {
6343 match self.candidates {
6344 Candidates::Files => {
6345 if self.include_ignored {
6346 self.snapshot.file_count()
6347 } else {
6348 self.snapshot.visible_file_count()
6349 }
6350 }
6351 Candidates::Directories => {
6352 if self.include_ignored {
6353 self.snapshot.dir_count()
6354 } else {
6355 self.snapshot.visible_dir_count()
6356 }
6357 }
6358 Candidates::Entries => {
6359 if self.include_ignored {
6360 self.snapshot.entry_count()
6361 } else {
6362 self.snapshot.visible_entry_count()
6363 }
6364 }
6365 }
6366 }
6367 fn prefix(&self) -> Arc<RelPath> {
6368 if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
6369 self.snapshot.root_name().into()
6370 } else {
6371 RelPath::empty().into()
6372 }
6373 }
6374 fn root_is_file(&self) -> bool {
6375 self.snapshot.root_entry().is_some_and(|f| f.is_file())
6376 }
6377 fn path_style(&self) -> PathStyle {
6378 self.snapshot.path_style()
6379 }
6380 fn candidates(&'a self, start: usize) -> Self::Candidates {
6381 PathMatchCandidateSetNucleoIter {
6382 traversal: match self.candidates {
6383 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
6384 Candidates::Files => self.snapshot.files(self.include_ignored, start),
6385 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
6386 },
6387 }
6388 }
6389}
6390
6391pub struct PathMatchCandidateSetNucleoIter<'a> {
6392 traversal: Traversal<'a>,
6393}
6394
6395impl<'a> Iterator for PathMatchCandidateSetNucleoIter<'a> {
6396 type Item = fuzzy_nucleo::PathMatchCandidate<'a>;
6397 fn next(&mut self) -> Option<Self::Item> {
6398 self.traversal
6399 .next()
6400 .map(|entry| fuzzy_nucleo::PathMatchCandidate {
6401 is_dir: entry.kind.is_dir(),
6402 path: &entry.path,
6403 })
6404 }
6405}
6406
6407impl EventEmitter<Event> for Project {}
6408
6409impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
6410 fn from(val: &'a ProjectPath) -> Self {
6411 SettingsLocation {
6412 worktree_id: val.worktree_id,
6413 path: val.path.as_ref(),
6414 }
6415 }
6416}
6417
6418impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
6419 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6420 Self {
6421 worktree_id,
6422 path: path.into(),
6423 }
6424 }
6425}
6426
6427/// ResolvedPath is a path that has been resolved to either a ProjectPath
6428/// or an AbsPath and that *exists*.
6429#[derive(Debug, Clone)]
6430pub enum ResolvedPath {
6431 ProjectPath {
6432 project_path: ProjectPath,
6433 is_dir: bool,
6434 },
6435 AbsPath {
6436 path: String,
6437 is_dir: bool,
6438 },
6439}
6440
6441impl ResolvedPath {
6442 pub fn abs_path(&self) -> Option<&str> {
6443 match self {
6444 Self::AbsPath { path, .. } => Some(path),
6445 _ => None,
6446 }
6447 }
6448
6449 pub fn into_abs_path(self) -> Option<String> {
6450 match self {
6451 Self::AbsPath { path, .. } => Some(path),
6452 _ => None,
6453 }
6454 }
6455
6456 pub fn project_path(&self) -> Option<&ProjectPath> {
6457 match self {
6458 Self::ProjectPath { project_path, .. } => Some(project_path),
6459 _ => None,
6460 }
6461 }
6462
6463 pub fn is_file(&self) -> bool {
6464 !self.is_dir()
6465 }
6466
6467 pub fn is_dir(&self) -> bool {
6468 match self {
6469 Self::ProjectPath { is_dir, .. } => *is_dir,
6470 Self::AbsPath { is_dir, .. } => *is_dir,
6471 }
6472 }
6473}
6474
6475impl ProjectItem for Buffer {
6476 fn try_open(
6477 project: &Entity<Project>,
6478 path: &ProjectPath,
6479 cx: &mut App,
6480 ) -> Option<Task<Result<Entity<Self>>>> {
6481 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
6482 }
6483
6484 fn entry_id(&self, _cx: &App) -> Option<ProjectEntryId> {
6485 File::from_dyn(self.file()).and_then(|file| file.project_entry_id())
6486 }
6487
6488 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
6489 let file = self.file()?;
6490
6491 (!matches!(file.disk_state(), DiskState::Historic { .. })).then(|| ProjectPath {
6492 worktree_id: file.worktree_id(cx),
6493 path: file.path().clone(),
6494 })
6495 }
6496
6497 fn is_dirty(&self) -> bool {
6498 self.is_dirty()
6499 }
6500}
6501
6502impl Completion {
6503 pub fn kind(&self) -> Option<CompletionItemKind> {
6504 self.source
6505 // `lsp::CompletionListItemDefaults` has no `kind` field
6506 .lsp_completion(false)
6507 .and_then(|lsp_completion| lsp_completion.kind)
6508 }
6509
6510 pub fn label(&self) -> Option<String> {
6511 self.source
6512 .lsp_completion(false)
6513 .map(|lsp_completion| lsp_completion.label.clone())
6514 }
6515
6516 /// A key that can be used to sort completions when displaying
6517 /// them to the user.
6518 pub fn sort_key(&self) -> (usize, &str) {
6519 const DEFAULT_KIND_KEY: usize = 4;
6520 let kind_key = self
6521 .kind()
6522 .and_then(|lsp_completion_kind| match lsp_completion_kind {
6523 lsp::CompletionItemKind::KEYWORD => Some(0),
6524 lsp::CompletionItemKind::VARIABLE => Some(1),
6525 lsp::CompletionItemKind::CONSTANT => Some(2),
6526 lsp::CompletionItemKind::PROPERTY => Some(3),
6527 _ => None,
6528 })
6529 .unwrap_or(DEFAULT_KIND_KEY);
6530 (kind_key, self.label.filter_text())
6531 }
6532
6533 /// Whether this completion is a snippet.
6534 pub fn is_snippet_kind(&self) -> bool {
6535 matches!(
6536 &self.source,
6537 CompletionSource::Lsp { lsp_completion, .. }
6538 if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
6539 )
6540 }
6541
6542 /// Whether this completion is a snippet or snippet-style LSP completion.
6543 pub fn is_snippet(&self) -> bool {
6544 self.source
6545 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
6546 .lsp_completion(true)
6547 .is_some_and(|lsp_completion| {
6548 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
6549 })
6550 }
6551
6552 /// Returns the corresponding color for this completion.
6553 ///
6554 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
6555 pub fn color(&self) -> Option<Hsla> {
6556 // `lsp::CompletionListItemDefaults` has no `kind` field
6557 let lsp_completion = self.source.lsp_completion(false)?;
6558 if lsp_completion.kind? == CompletionItemKind::COLOR {
6559 return color_extractor::extract_color(&lsp_completion);
6560 }
6561 None
6562 }
6563}
6564
6565fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
6566 match level {
6567 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
6568 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
6569 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
6570 }
6571}
6572
6573fn provide_inline_values(
6574 captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
6575 snapshot: &language::BufferSnapshot,
6576 max_row: usize,
6577) -> Vec<InlineValueLocation> {
6578 let mut variables = Vec::new();
6579 let mut variable_position = HashSet::default();
6580 let mut scopes = Vec::new();
6581
6582 let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
6583
6584 for (capture_range, capture_kind) in captures {
6585 match capture_kind {
6586 language::DebuggerTextObject::Variable => {
6587 let variable_name = snapshot
6588 .text_for_range(capture_range.clone())
6589 .collect::<String>();
6590 let point = snapshot.offset_to_point(capture_range.end);
6591
6592 while scopes
6593 .last()
6594 .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
6595 {
6596 scopes.pop();
6597 }
6598
6599 if point.row as usize > max_row {
6600 break;
6601 }
6602
6603 let scope = if scopes
6604 .last()
6605 .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
6606 {
6607 VariableScope::Global
6608 } else {
6609 VariableScope::Local
6610 };
6611
6612 if variable_position.insert(capture_range.end) {
6613 variables.push(InlineValueLocation {
6614 variable_name,
6615 scope,
6616 lookup: VariableLookupKind::Variable,
6617 row: point.row as usize,
6618 column: point.column as usize,
6619 });
6620 }
6621 }
6622 language::DebuggerTextObject::Scope => {
6623 while scopes.last().map_or_else(
6624 || false,
6625 |scope: &Range<usize>| {
6626 !(scope.contains(&capture_range.start)
6627 && scope.contains(&capture_range.end))
6628 },
6629 ) {
6630 scopes.pop();
6631 }
6632 scopes.push(capture_range);
6633 }
6634 }
6635 }
6636
6637 variables
6638}