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