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<Option<TrashedEntry>>>> {
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<Option<TrashedEntry>>>> {
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 restore_entry(
2590 &self,
2591 worktree_id: WorktreeId,
2592 trash_entry: TrashedEntry,
2593 cx: &mut Context<'_, Self>,
2594 ) -> Task<Result<ProjectPath>> {
2595 let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {
2596 return Task::ready(Err(anyhow!("No worktree for id {worktree_id:?}")));
2597 };
2598
2599 cx.spawn(async move |_, cx| {
2600 Worktree::restore_entry(trash_entry, worktree, cx)
2601 .await
2602 .map(|rel_path_buf| ProjectPath {
2603 worktree_id: worktree_id,
2604 path: Arc::from(rel_path_buf.as_rel_path()),
2605 })
2606 })
2607 }
2608
2609 #[inline]
2610 pub fn expand_entry(
2611 &mut self,
2612 worktree_id: WorktreeId,
2613 entry_id: ProjectEntryId,
2614 cx: &mut Context<Self>,
2615 ) -> Option<Task<Result<()>>> {
2616 let worktree = self.worktree_for_id(worktree_id, cx)?;
2617 worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
2618 }
2619
2620 pub fn expand_all_for_entry(
2621 &mut self,
2622 worktree_id: WorktreeId,
2623 entry_id: ProjectEntryId,
2624 cx: &mut Context<Self>,
2625 ) -> Option<Task<Result<()>>> {
2626 let worktree = self.worktree_for_id(worktree_id, cx)?;
2627 let task = worktree.update(cx, |worktree, cx| {
2628 worktree.expand_all_for_entry(entry_id, cx)
2629 });
2630 Some(cx.spawn(async move |this, cx| {
2631 task.context("no task")?.await?;
2632 this.update(cx, |_, cx| {
2633 cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
2634 })?;
2635 Ok(())
2636 }))
2637 }
2638
2639 pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2640 anyhow::ensure!(
2641 matches!(self.client_state, ProjectClientState::Local),
2642 "project was already shared"
2643 );
2644
2645 self.client_subscriptions.extend([
2646 self.collab_client
2647 .subscribe_to_entity(project_id)?
2648 .set_entity(&cx.entity(), &cx.to_async()),
2649 self.collab_client
2650 .subscribe_to_entity(project_id)?
2651 .set_entity(&self.worktree_store, &cx.to_async()),
2652 self.collab_client
2653 .subscribe_to_entity(project_id)?
2654 .set_entity(&self.buffer_store, &cx.to_async()),
2655 self.collab_client
2656 .subscribe_to_entity(project_id)?
2657 .set_entity(&self.lsp_store, &cx.to_async()),
2658 self.collab_client
2659 .subscribe_to_entity(project_id)?
2660 .set_entity(&self.settings_observer, &cx.to_async()),
2661 self.collab_client
2662 .subscribe_to_entity(project_id)?
2663 .set_entity(&self.dap_store, &cx.to_async()),
2664 self.collab_client
2665 .subscribe_to_entity(project_id)?
2666 .set_entity(&self.breakpoint_store, &cx.to_async()),
2667 self.collab_client
2668 .subscribe_to_entity(project_id)?
2669 .set_entity(&self.git_store, &cx.to_async()),
2670 ]);
2671
2672 self.buffer_store.update(cx, |buffer_store, cx| {
2673 buffer_store.shared(project_id, self.collab_client.clone().into(), cx)
2674 });
2675 self.worktree_store.update(cx, |worktree_store, cx| {
2676 worktree_store.shared(project_id, self.collab_client.clone().into(), cx);
2677 });
2678 self.lsp_store.update(cx, |lsp_store, cx| {
2679 lsp_store.shared(project_id, self.collab_client.clone().into(), cx)
2680 });
2681 self.breakpoint_store.update(cx, |breakpoint_store, _| {
2682 breakpoint_store.shared(project_id, self.collab_client.clone().into())
2683 });
2684 self.dap_store.update(cx, |dap_store, cx| {
2685 dap_store.shared(project_id, self.collab_client.clone().into(), cx);
2686 });
2687 self.task_store.update(cx, |task_store, cx| {
2688 task_store.shared(project_id, self.collab_client.clone().into(), cx);
2689 });
2690 self.settings_observer.update(cx, |settings_observer, cx| {
2691 settings_observer.shared(project_id, self.collab_client.clone().into(), cx)
2692 });
2693 self.git_store.update(cx, |git_store, cx| {
2694 git_store.shared(project_id, self.collab_client.clone().into(), cx)
2695 });
2696
2697 self.client_state = ProjectClientState::Shared {
2698 remote_id: project_id,
2699 };
2700
2701 cx.emit(Event::RemoteIdChanged(Some(project_id)));
2702 Ok(())
2703 }
2704
2705 pub fn reshared(
2706 &mut self,
2707 message: proto::ResharedProject,
2708 cx: &mut Context<Self>,
2709 ) -> Result<()> {
2710 self.buffer_store
2711 .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2712 self.set_collaborators_from_proto(message.collaborators, cx)?;
2713
2714 self.worktree_store.update(cx, |worktree_store, cx| {
2715 worktree_store.send_project_updates(cx);
2716 });
2717 if let Some(remote_id) = self.remote_id() {
2718 self.git_store.update(cx, |git_store, cx| {
2719 git_store.shared(remote_id, self.collab_client.clone().into(), cx)
2720 });
2721 }
2722 cx.emit(Event::Reshared);
2723 Ok(())
2724 }
2725
2726 pub fn rejoined(
2727 &mut self,
2728 message: proto::RejoinedProject,
2729 message_id: u32,
2730 cx: &mut Context<Self>,
2731 ) -> Result<()> {
2732 cx.update_global::<SettingsStore, _>(|store, cx| {
2733 for worktree_metadata in &message.worktrees {
2734 store
2735 .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
2736 .log_err();
2737 }
2738 });
2739
2740 self.join_project_response_message_id = message_id;
2741 self.set_worktrees_from_proto(message.worktrees, cx)?;
2742 self.set_collaborators_from_proto(message.collaborators, cx)?;
2743
2744 let project = cx.weak_entity();
2745 self.lsp_store.update(cx, |lsp_store, cx| {
2746 lsp_store.set_language_server_statuses_from_proto(
2747 project,
2748 message.language_servers,
2749 message.language_server_capabilities,
2750 cx,
2751 )
2752 });
2753 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2754 .unwrap();
2755 cx.emit(Event::Rejoined);
2756 Ok(())
2757 }
2758
2759 #[inline]
2760 pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2761 self.unshare_internal(cx)?;
2762 cx.emit(Event::RemoteIdChanged(None));
2763 Ok(())
2764 }
2765
2766 fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2767 anyhow::ensure!(
2768 !self.is_via_collab(),
2769 "attempted to unshare a remote project"
2770 );
2771
2772 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2773 self.client_state = ProjectClientState::Local;
2774 self.collaborators.clear();
2775 self.client_subscriptions.clear();
2776 self.worktree_store.update(cx, |store, cx| {
2777 store.unshared(cx);
2778 });
2779 self.buffer_store.update(cx, |buffer_store, cx| {
2780 buffer_store.forget_shared_buffers();
2781 buffer_store.unshared(cx)
2782 });
2783 self.task_store.update(cx, |task_store, cx| {
2784 task_store.unshared(cx);
2785 });
2786 self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2787 breakpoint_store.unshared(cx);
2788 });
2789 self.dap_store.update(cx, |dap_store, cx| {
2790 dap_store.unshared(cx);
2791 });
2792 self.settings_observer.update(cx, |settings_observer, cx| {
2793 settings_observer.unshared(cx);
2794 });
2795 self.git_store.update(cx, |git_store, cx| {
2796 git_store.unshared(cx);
2797 });
2798
2799 self.collab_client
2800 .send(proto::UnshareProject {
2801 project_id: remote_id,
2802 })
2803 .ok();
2804 Ok(())
2805 } else {
2806 anyhow::bail!("attempted to unshare an unshared project");
2807 }
2808 }
2809
2810 pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2811 if self.is_disconnected(cx) {
2812 return;
2813 }
2814 self.disconnected_from_host_internal(cx);
2815 cx.emit(Event::DisconnectedFromHost);
2816 }
2817
2818 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2819 let new_capability =
2820 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2821 Capability::ReadWrite
2822 } else {
2823 Capability::ReadOnly
2824 };
2825 if let ProjectClientState::Collab { capability, .. } = &mut self.client_state {
2826 if *capability == new_capability {
2827 return;
2828 }
2829
2830 *capability = new_capability;
2831 for buffer in self.opened_buffers(cx) {
2832 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2833 }
2834 }
2835 }
2836
2837 fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2838 if let ProjectClientState::Collab {
2839 sharing_has_stopped,
2840 ..
2841 } = &mut self.client_state
2842 {
2843 *sharing_has_stopped = true;
2844 self.client_subscriptions.clear();
2845 self.collaborators.clear();
2846 self.worktree_store.update(cx, |store, cx| {
2847 store.disconnected_from_host(cx);
2848 });
2849 self.buffer_store.update(cx, |buffer_store, cx| {
2850 buffer_store.disconnected_from_host(cx)
2851 });
2852 self.lsp_store
2853 .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2854 }
2855 }
2856
2857 #[inline]
2858 pub fn close(&mut self, cx: &mut Context<Self>) {
2859 cx.emit(Event::Closed);
2860 }
2861
2862 #[inline]
2863 pub fn is_disconnected(&self, cx: &App) -> bool {
2864 match &self.client_state {
2865 ProjectClientState::Collab {
2866 sharing_has_stopped,
2867 ..
2868 } => *sharing_has_stopped,
2869 ProjectClientState::Local if self.is_via_remote_server() => {
2870 self.remote_client_is_disconnected(cx)
2871 }
2872 _ => false,
2873 }
2874 }
2875
2876 #[inline]
2877 fn remote_client_is_disconnected(&self, cx: &App) -> bool {
2878 self.remote_client
2879 .as_ref()
2880 .map(|remote| remote.read(cx).is_disconnected())
2881 .unwrap_or(false)
2882 }
2883
2884 #[inline]
2885 pub fn capability(&self) -> Capability {
2886 match &self.client_state {
2887 ProjectClientState::Collab { capability, .. } => *capability,
2888 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2889 }
2890 }
2891
2892 #[inline]
2893 pub fn is_read_only(&self, cx: &App) -> bool {
2894 self.is_disconnected(cx) || !self.capability().editable()
2895 }
2896
2897 #[inline]
2898 pub fn is_local(&self) -> bool {
2899 match &self.client_state {
2900 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2901 self.remote_client.is_none()
2902 }
2903 ProjectClientState::Collab { .. } => false,
2904 }
2905 }
2906
2907 /// Whether this project is a remote server (not counting collab).
2908 #[inline]
2909 pub fn is_via_remote_server(&self) -> bool {
2910 match &self.client_state {
2911 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2912 self.remote_client.is_some()
2913 }
2914 ProjectClientState::Collab { .. } => false,
2915 }
2916 }
2917
2918 /// Whether this project is from collab (not counting remote servers).
2919 #[inline]
2920 pub fn is_via_collab(&self) -> bool {
2921 match &self.client_state {
2922 ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2923 ProjectClientState::Collab { .. } => true,
2924 }
2925 }
2926
2927 /// `!self.is_local()`
2928 #[inline]
2929 pub fn is_remote(&self) -> bool {
2930 debug_assert_eq!(
2931 !self.is_local(),
2932 self.is_via_collab() || self.is_via_remote_server()
2933 );
2934 !self.is_local()
2935 }
2936
2937 #[inline]
2938 pub fn is_via_wsl_with_host_interop(&self, cx: &App) -> bool {
2939 match &self.client_state {
2940 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2941 matches!(
2942 &self.remote_client, Some(remote_client)
2943 if remote_client.read(cx).has_wsl_interop()
2944 )
2945 }
2946 _ => false,
2947 }
2948 }
2949
2950 pub fn disable_worktree_scanner(&mut self, cx: &mut Context<Self>) {
2951 self.worktree_store.update(cx, |worktree_store, _cx| {
2952 worktree_store.disable_scanner();
2953 });
2954 }
2955
2956 #[inline]
2957 pub fn create_buffer(
2958 &mut self,
2959 language: Option<Arc<Language>>,
2960 project_searchable: bool,
2961 cx: &mut Context<Self>,
2962 ) -> Task<Result<Entity<Buffer>>> {
2963 self.buffer_store.update(cx, |buffer_store, cx| {
2964 buffer_store.create_buffer(language, project_searchable, cx)
2965 })
2966 }
2967
2968 #[inline]
2969 pub fn create_local_buffer(
2970 &mut self,
2971 text: &str,
2972 language: Option<Arc<Language>>,
2973 project_searchable: bool,
2974 cx: &mut Context<Self>,
2975 ) -> Entity<Buffer> {
2976 if self.is_remote() {
2977 panic!("called create_local_buffer on a remote project")
2978 }
2979 self.buffer_store.update(cx, |buffer_store, cx| {
2980 buffer_store.create_local_buffer(text, language, project_searchable, cx)
2981 })
2982 }
2983
2984 pub fn open_path(
2985 &mut self,
2986 path: ProjectPath,
2987 cx: &mut Context<Self>,
2988 ) -> Task<Result<(Option<ProjectEntryId>, Entity<Buffer>)>> {
2989 let task = self.open_buffer(path, cx);
2990 cx.spawn(async move |_project, cx| {
2991 let buffer = task.await?;
2992 let project_entry_id = buffer.read_with(cx, |buffer, _cx| {
2993 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id())
2994 });
2995
2996 Ok((project_entry_id, buffer))
2997 })
2998 }
2999
3000 pub fn open_local_buffer(
3001 &mut self,
3002 abs_path: impl AsRef<Path>,
3003 cx: &mut Context<Self>,
3004 ) -> Task<Result<Entity<Buffer>>> {
3005 let worktree_task = self.find_or_create_worktree(abs_path.as_ref(), false, cx);
3006 cx.spawn(async move |this, cx| {
3007 let (worktree, relative_path) = worktree_task.await?;
3008 this.update(cx, |this, cx| {
3009 this.open_buffer((worktree.read(cx).id(), relative_path), cx)
3010 })?
3011 .await
3012 })
3013 }
3014
3015 #[cfg(feature = "test-support")]
3016 pub fn open_local_buffer_with_lsp(
3017 &mut self,
3018 abs_path: impl AsRef<Path>,
3019 cx: &mut Context<Self>,
3020 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
3021 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
3022 self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
3023 } else {
3024 Task::ready(Err(anyhow!("no such path")))
3025 }
3026 }
3027
3028 pub fn download_file(
3029 &mut self,
3030 worktree_id: WorktreeId,
3031 path: Arc<RelPath>,
3032 destination_path: PathBuf,
3033 cx: &mut Context<Self>,
3034 ) -> Task<Result<()>> {
3035 log::debug!(
3036 "download_file called: worktree_id={:?}, path={:?}, destination={:?}",
3037 worktree_id,
3038 path,
3039 destination_path
3040 );
3041
3042 let Some(remote_client) = &self.remote_client else {
3043 log::error!("download_file: not a remote project");
3044 return Task::ready(Err(anyhow!("not a remote project")));
3045 };
3046
3047 let proto_client = remote_client.read(cx).proto_client();
3048 // For SSH remote projects, use REMOTE_SERVER_PROJECT_ID instead of remote_id()
3049 // because SSH projects have client_state: Local but still need to communicate with remote server
3050 let project_id = self.remote_id().unwrap_or(REMOTE_SERVER_PROJECT_ID);
3051 let downloading_files = self.downloading_files.clone();
3052 let path_str = path.to_proto();
3053
3054 static NEXT_FILE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
3055 let file_id = NEXT_FILE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
3056
3057 // Register BEFORE sending request to avoid race condition
3058 let key = (worktree_id, path_str.clone());
3059 log::debug!(
3060 "download_file: pre-registering download with key={:?}, file_id={}",
3061 key,
3062 file_id
3063 );
3064 downloading_files.lock().insert(
3065 key,
3066 DownloadingFile {
3067 destination_path: destination_path,
3068 chunks: Vec::new(),
3069 total_size: 0,
3070 file_id: Some(file_id),
3071 },
3072 );
3073 log::debug!(
3074 "download_file: sending DownloadFileByPath request, path_str={}",
3075 path_str
3076 );
3077
3078 cx.spawn(async move |_this, _cx| {
3079 log::debug!("download_file: sending request with file_id={}...", file_id);
3080 let response = proto_client
3081 .request(proto::DownloadFileByPath {
3082 project_id,
3083 worktree_id: worktree_id.to_proto(),
3084 path: path_str.clone(),
3085 file_id,
3086 })
3087 .await?;
3088
3089 log::debug!("download_file: got response, file_id={}", response.file_id);
3090 // The file_id is set from the State message, we just confirm the request succeeded
3091 Ok(())
3092 })
3093 }
3094
3095 #[ztracing::instrument(skip_all)]
3096 pub fn open_buffer(
3097 &mut self,
3098 path: impl Into<ProjectPath>,
3099 cx: &mut App,
3100 ) -> Task<Result<Entity<Buffer>>> {
3101 if self.is_disconnected(cx) {
3102 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3103 }
3104
3105 self.buffer_store.update(cx, |buffer_store, cx| {
3106 buffer_store.open_buffer(path.into(), cx)
3107 })
3108 }
3109
3110 #[cfg(feature = "test-support")]
3111 pub fn open_buffer_with_lsp(
3112 &mut self,
3113 path: impl Into<ProjectPath>,
3114 cx: &mut Context<Self>,
3115 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
3116 let buffer = self.open_buffer(path, cx);
3117 cx.spawn(async move |this, cx| {
3118 let buffer = buffer.await?;
3119 let handle = this.update(cx, |project, cx| {
3120 project.register_buffer_with_language_servers(&buffer, cx)
3121 })?;
3122 Ok((buffer, handle))
3123 })
3124 }
3125
3126 pub fn register_buffer_with_language_servers(
3127 &self,
3128 buffer: &Entity<Buffer>,
3129 cx: &mut App,
3130 ) -> OpenLspBufferHandle {
3131 self.lsp_store.update(cx, |lsp_store, cx| {
3132 lsp_store.register_buffer_with_language_servers(buffer, HashSet::default(), false, cx)
3133 })
3134 }
3135
3136 pub fn open_unstaged_diff(
3137 &mut self,
3138 buffer: Entity<Buffer>,
3139 cx: &mut Context<Self>,
3140 ) -> Task<Result<Entity<BufferDiff>>> {
3141 if self.is_disconnected(cx) {
3142 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3143 }
3144 self.git_store
3145 .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
3146 }
3147
3148 #[ztracing::instrument(skip_all)]
3149 pub fn open_uncommitted_diff(
3150 &mut self,
3151 buffer: Entity<Buffer>,
3152 cx: &mut Context<Self>,
3153 ) -> Task<Result<Entity<BufferDiff>>> {
3154 if self.is_disconnected(cx) {
3155 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3156 }
3157 self.git_store.update(cx, |git_store, cx| {
3158 git_store.open_uncommitted_diff(buffer, cx)
3159 })
3160 }
3161
3162 pub fn open_buffer_by_id(
3163 &mut self,
3164 id: BufferId,
3165 cx: &mut Context<Self>,
3166 ) -> Task<Result<Entity<Buffer>>> {
3167 if let Some(buffer) = self.buffer_for_id(id, cx) {
3168 Task::ready(Ok(buffer))
3169 } else if self.is_local() || self.is_via_remote_server() {
3170 Task::ready(Err(anyhow!("buffer {id} does not exist")))
3171 } else if let Some(project_id) = self.remote_id() {
3172 let request = self.collab_client.request(proto::OpenBufferById {
3173 project_id,
3174 id: id.into(),
3175 });
3176 cx.spawn(async move |project, cx| {
3177 let buffer_id = BufferId::new(request.await?.buffer_id)?;
3178 project
3179 .update(cx, |project, cx| {
3180 project.buffer_store.update(cx, |buffer_store, cx| {
3181 buffer_store.wait_for_remote_buffer(buffer_id, cx)
3182 })
3183 })?
3184 .await
3185 })
3186 } else {
3187 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
3188 }
3189 }
3190
3191 pub fn save_buffers(
3192 &self,
3193 buffers: HashSet<Entity<Buffer>>,
3194 cx: &mut Context<Self>,
3195 ) -> Task<Result<()>> {
3196 cx.spawn(async move |this, cx| {
3197 let save_tasks = buffers.into_iter().filter_map(|buffer| {
3198 this.update(cx, |this, cx| this.save_buffer(buffer, cx))
3199 .ok()
3200 });
3201 try_join_all(save_tasks).await?;
3202 Ok(())
3203 })
3204 }
3205
3206 pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
3207 self.buffer_store
3208 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
3209 }
3210
3211 pub fn save_buffer_as(
3212 &mut self,
3213 buffer: Entity<Buffer>,
3214 path: ProjectPath,
3215 cx: &mut Context<Self>,
3216 ) -> Task<Result<()>> {
3217 self.buffer_store.update(cx, |buffer_store, cx| {
3218 buffer_store.save_buffer_as(buffer.clone(), path, cx)
3219 })
3220 }
3221
3222 pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
3223 self.buffer_store.read(cx).get_by_path(path)
3224 }
3225
3226 fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3227 {
3228 let mut remotely_created_models = self.remotely_created_models.lock();
3229 if remotely_created_models.retain_count > 0 {
3230 remotely_created_models.buffers.push(buffer.clone())
3231 }
3232 }
3233
3234 self.request_buffer_diff_recalculation(buffer, cx);
3235
3236 cx.subscribe(buffer, |this, buffer, event, cx| {
3237 this.on_buffer_event(buffer, event, cx);
3238 })
3239 .detach();
3240
3241 Ok(())
3242 }
3243
3244 pub fn open_image(
3245 &mut self,
3246 path: impl Into<ProjectPath>,
3247 cx: &mut Context<Self>,
3248 ) -> Task<Result<Entity<ImageItem>>> {
3249 if self.is_disconnected(cx) {
3250 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3251 }
3252
3253 let open_image_task = self.image_store.update(cx, |image_store, cx| {
3254 image_store.open_image(path.into(), cx)
3255 });
3256
3257 let weak_project = cx.entity().downgrade();
3258 cx.spawn(async move |_, cx| {
3259 let image_item = open_image_task.await?;
3260
3261 // Check if metadata already exists (e.g., for remote images)
3262 let needs_metadata =
3263 cx.read_entity(&image_item, |item, _| item.image_metadata.is_none());
3264
3265 if needs_metadata {
3266 let project = weak_project.upgrade().context("Project dropped")?;
3267 let metadata =
3268 ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
3269 image_item.update(cx, |image_item, cx| {
3270 image_item.image_metadata = Some(metadata);
3271 cx.emit(ImageItemEvent::MetadataUpdated);
3272 });
3273 }
3274
3275 Ok(image_item)
3276 })
3277 }
3278
3279 async fn send_buffer_ordered_messages(
3280 project: WeakEntity<Self>,
3281 rx: UnboundedReceiver<BufferOrderedMessage>,
3282 cx: &mut AsyncApp,
3283 ) -> Result<()> {
3284 const MAX_BATCH_SIZE: usize = 128;
3285
3286 let mut operations_by_buffer_id = HashMap::default();
3287 async fn flush_operations(
3288 this: &WeakEntity<Project>,
3289 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
3290 needs_resync_with_host: &mut bool,
3291 is_local: bool,
3292 cx: &mut AsyncApp,
3293 ) -> Result<()> {
3294 for (buffer_id, operations) in operations_by_buffer_id.drain() {
3295 let request = this.read_with(cx, |this, _| {
3296 let project_id = this.remote_id()?;
3297 Some(this.collab_client.request(proto::UpdateBuffer {
3298 buffer_id: buffer_id.into(),
3299 project_id,
3300 operations,
3301 }))
3302 })?;
3303 if let Some(request) = request
3304 && request.await.is_err()
3305 && !is_local
3306 {
3307 *needs_resync_with_host = true;
3308 break;
3309 }
3310 }
3311 Ok(())
3312 }
3313
3314 let mut needs_resync_with_host = false;
3315 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
3316
3317 while let Some(changes) = changes.next().await {
3318 let is_local = project.read_with(cx, |this, _| this.is_local())?;
3319
3320 for change in changes {
3321 match change {
3322 BufferOrderedMessage::Operation {
3323 buffer_id,
3324 operation,
3325 } => {
3326 if needs_resync_with_host {
3327 continue;
3328 }
3329
3330 operations_by_buffer_id
3331 .entry(buffer_id)
3332 .or_insert(Vec::new())
3333 .push(operation);
3334 }
3335
3336 BufferOrderedMessage::Resync => {
3337 operations_by_buffer_id.clear();
3338 if project
3339 .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
3340 .await
3341 .is_ok()
3342 {
3343 needs_resync_with_host = false;
3344 }
3345 }
3346
3347 BufferOrderedMessage::LanguageServerUpdate {
3348 language_server_id,
3349 message,
3350 name,
3351 } => {
3352 flush_operations(
3353 &project,
3354 &mut operations_by_buffer_id,
3355 &mut needs_resync_with_host,
3356 is_local,
3357 cx,
3358 )
3359 .await?;
3360
3361 project.read_with(cx, |project, _| {
3362 if let Some(project_id) = project.remote_id() {
3363 project
3364 .collab_client
3365 .send(proto::UpdateLanguageServer {
3366 project_id,
3367 server_name: name.map(|name| String::from(name.0)),
3368 language_server_id: language_server_id.to_proto(),
3369 variant: Some(message),
3370 })
3371 .log_err();
3372 }
3373 })?;
3374 }
3375 }
3376 }
3377
3378 flush_operations(
3379 &project,
3380 &mut operations_by_buffer_id,
3381 &mut needs_resync_with_host,
3382 is_local,
3383 cx,
3384 )
3385 .await?;
3386 }
3387
3388 Ok(())
3389 }
3390
3391 fn on_buffer_store_event(
3392 &mut self,
3393 _: Entity<BufferStore>,
3394 event: &BufferStoreEvent,
3395 cx: &mut Context<Self>,
3396 ) {
3397 match event {
3398 BufferStoreEvent::BufferAdded(buffer) => {
3399 self.register_buffer(buffer, cx).log_err();
3400 }
3401 BufferStoreEvent::BufferDropped(buffer_id) => {
3402 if let Some(ref remote_client) = self.remote_client {
3403 remote_client
3404 .read(cx)
3405 .proto_client()
3406 .send(proto::CloseBuffer {
3407 project_id: 0,
3408 buffer_id: buffer_id.to_proto(),
3409 })
3410 .log_err();
3411 }
3412 }
3413 _ => {}
3414 }
3415 }
3416
3417 fn on_image_store_event(
3418 &mut self,
3419 _: Entity<ImageStore>,
3420 event: &ImageStoreEvent,
3421 cx: &mut Context<Self>,
3422 ) {
3423 match event {
3424 ImageStoreEvent::ImageAdded(image) => {
3425 cx.subscribe(image, |this, image, event, cx| {
3426 this.on_image_event(image, event, cx);
3427 })
3428 .detach();
3429 }
3430 }
3431 }
3432
3433 fn on_dap_store_event(
3434 &mut self,
3435 _: Entity<DapStore>,
3436 event: &DapStoreEvent,
3437 cx: &mut Context<Self>,
3438 ) {
3439 if let DapStoreEvent::Notification(message) = event {
3440 cx.emit(Event::Toast {
3441 notification_id: "dap".into(),
3442 message: message.clone(),
3443 link: None,
3444 });
3445 }
3446 }
3447
3448 fn on_lsp_store_event(
3449 &mut self,
3450 _: Entity<LspStore>,
3451 event: &LspStoreEvent,
3452 cx: &mut Context<Self>,
3453 ) {
3454 match event {
3455 LspStoreEvent::DiagnosticsUpdated { server_id, paths } => {
3456 cx.emit(Event::DiagnosticsUpdated {
3457 paths: paths.clone(),
3458 language_server_id: *server_id,
3459 })
3460 }
3461 LspStoreEvent::LanguageServerAdded(server_id, name, worktree_id) => cx.emit(
3462 Event::LanguageServerAdded(*server_id, name.clone(), *worktree_id),
3463 ),
3464 LspStoreEvent::LanguageServerRemoved(server_id) => {
3465 cx.emit(Event::LanguageServerRemoved(*server_id))
3466 }
3467 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
3468 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
3469 ),
3470 LspStoreEvent::LanguageDetected {
3471 buffer,
3472 new_language,
3473 } => {
3474 let Some(_) = new_language else {
3475 cx.emit(Event::LanguageNotFound(buffer.clone()));
3476 return;
3477 };
3478 }
3479 LspStoreEvent::RefreshInlayHints {
3480 server_id,
3481 request_id,
3482 } => cx.emit(Event::RefreshInlayHints {
3483 server_id: *server_id,
3484 request_id: *request_id,
3485 }),
3486 LspStoreEvent::RefreshSemanticTokens {
3487 server_id,
3488 request_id,
3489 } => cx.emit(Event::RefreshSemanticTokens {
3490 server_id: *server_id,
3491 request_id: *request_id,
3492 }),
3493 LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
3494 LspStoreEvent::LanguageServerPrompt(prompt) => {
3495 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
3496 }
3497 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
3498 cx.emit(Event::DiskBasedDiagnosticsStarted {
3499 language_server_id: *language_server_id,
3500 });
3501 }
3502 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
3503 cx.emit(Event::DiskBasedDiagnosticsFinished {
3504 language_server_id: *language_server_id,
3505 });
3506 }
3507 LspStoreEvent::LanguageServerUpdate {
3508 language_server_id,
3509 name,
3510 message,
3511 } => {
3512 if self.is_local() {
3513 self.enqueue_buffer_ordered_message(
3514 BufferOrderedMessage::LanguageServerUpdate {
3515 language_server_id: *language_server_id,
3516 message: message.clone(),
3517 name: name.clone(),
3518 },
3519 )
3520 .ok();
3521 }
3522
3523 match message {
3524 proto::update_language_server::Variant::MetadataUpdated(update) => {
3525 self.lsp_store.update(cx, |lsp_store, _| {
3526 if let Some(capabilities) = update
3527 .capabilities
3528 .as_ref()
3529 .and_then(|capabilities| serde_json::from_str(capabilities).ok())
3530 {
3531 lsp_store
3532 .lsp_server_capabilities
3533 .insert(*language_server_id, capabilities);
3534 }
3535
3536 if let Some(language_server_status) = lsp_store
3537 .language_server_statuses
3538 .get_mut(language_server_id)
3539 {
3540 if let Some(binary) = &update.binary {
3541 language_server_status.binary = Some(LanguageServerBinary {
3542 path: PathBuf::from(&binary.path),
3543 arguments: binary
3544 .arguments
3545 .iter()
3546 .map(OsString::from)
3547 .collect(),
3548 env: None,
3549 });
3550 }
3551
3552 language_server_status.configuration = update
3553 .configuration
3554 .as_ref()
3555 .and_then(|config_str| serde_json::from_str(config_str).ok());
3556
3557 language_server_status.workspace_folders = update
3558 .workspace_folders
3559 .iter()
3560 .filter_map(|uri_str| lsp::Uri::from_str(uri_str).ok())
3561 .collect();
3562 }
3563 });
3564 }
3565 proto::update_language_server::Variant::RegisteredForBuffer(update) => {
3566 if let Some(buffer_id) = BufferId::new(update.buffer_id).ok() {
3567 cx.emit(Event::LanguageServerBufferRegistered {
3568 buffer_id,
3569 server_id: *language_server_id,
3570 buffer_abs_path: PathBuf::from(&update.buffer_abs_path),
3571 name: name.clone(),
3572 });
3573 }
3574 }
3575 _ => (),
3576 }
3577 }
3578 LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
3579 notification_id: "lsp".into(),
3580 message: message.clone(),
3581 link: None,
3582 }),
3583 LspStoreEvent::SnippetEdit {
3584 buffer_id,
3585 edits,
3586 most_recent_edit,
3587 } => {
3588 if most_recent_edit.replica_id == self.replica_id() {
3589 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
3590 }
3591 }
3592 LspStoreEvent::WorkspaceEditApplied(transaction) => {
3593 cx.emit(Event::WorkspaceEditApplied(transaction.clone()))
3594 }
3595 }
3596 }
3597
3598 fn on_remote_client_event(
3599 &mut self,
3600 _: Entity<RemoteClient>,
3601 event: &remote::RemoteClientEvent,
3602 cx: &mut Context<Self>,
3603 ) {
3604 match event {
3605 &remote::RemoteClientEvent::Disconnected { server_not_running } => {
3606 self.worktree_store.update(cx, |store, cx| {
3607 store.disconnected_from_host(cx);
3608 });
3609 self.buffer_store.update(cx, |buffer_store, cx| {
3610 buffer_store.disconnected_from_host(cx)
3611 });
3612 self.lsp_store.update(cx, |lsp_store, _cx| {
3613 lsp_store.disconnected_from_ssh_remote()
3614 });
3615 cx.emit(Event::DisconnectedFromRemote { server_not_running });
3616 }
3617 }
3618 }
3619
3620 fn on_settings_observer_event(
3621 &mut self,
3622 _: Entity<SettingsObserver>,
3623 event: &SettingsObserverEvent,
3624 cx: &mut Context<Self>,
3625 ) {
3626 match event {
3627 SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
3628 Err(InvalidSettingsError::LocalSettings { message, path }) => {
3629 let message = format!("Failed to set local settings in {path:?}:\n{message}");
3630 cx.emit(Event::Toast {
3631 notification_id: format!("local-settings-{path:?}").into(),
3632 link: None,
3633 message,
3634 });
3635 }
3636 Ok(path) => cx.emit(Event::HideToast {
3637 notification_id: format!("local-settings-{path:?}").into(),
3638 }),
3639 Err(_) => {}
3640 },
3641 SettingsObserverEvent::LocalTasksUpdated(result) => match result {
3642 Err(InvalidSettingsError::Tasks { message, path }) => {
3643 let message = format!("Failed to set local tasks in {path:?}:\n{message}");
3644 cx.emit(Event::Toast {
3645 notification_id: format!("local-tasks-{path:?}").into(),
3646 link: Some(ToastLink {
3647 label: "Open Tasks Documentation",
3648 url: "https://zed.dev/docs/tasks",
3649 }),
3650 message,
3651 });
3652 }
3653 Ok(path) => cx.emit(Event::HideToast {
3654 notification_id: format!("local-tasks-{path:?}").into(),
3655 }),
3656 Err(_) => {}
3657 },
3658 SettingsObserverEvent::LocalDebugScenariosUpdated(result) => match result {
3659 Err(InvalidSettingsError::Debug { message, path }) => {
3660 let message =
3661 format!("Failed to set local debug scenarios in {path:?}:\n{message}");
3662 cx.emit(Event::Toast {
3663 notification_id: format!("local-debug-scenarios-{path:?}").into(),
3664 link: None,
3665 message,
3666 });
3667 }
3668 Ok(path) => cx.emit(Event::HideToast {
3669 notification_id: format!("local-debug-scenarios-{path:?}").into(),
3670 }),
3671 Err(_) => {}
3672 },
3673 }
3674 }
3675
3676 fn on_worktree_store_event(
3677 &mut self,
3678 _: Entity<WorktreeStore>,
3679 event: &WorktreeStoreEvent,
3680 cx: &mut Context<Self>,
3681 ) {
3682 match event {
3683 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3684 self.on_worktree_added(worktree, cx);
3685 cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
3686 }
3687 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
3688 cx.emit(Event::WorktreeRemoved(*id));
3689 }
3690 WorktreeStoreEvent::WorktreeReleased(_, id) => {
3691 self.on_worktree_released(*id, cx);
3692 }
3693 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
3694 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
3695 WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
3696 self.client()
3697 .telemetry()
3698 .report_discovered_project_type_events(*worktree_id, changes);
3699 cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
3700 }
3701 WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
3702 cx.emit(Event::DeletedEntry(*worktree_id, *id))
3703 }
3704 // Listen to the GitStore instead.
3705 WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
3706 WorktreeStoreEvent::WorktreeUpdatedRootRepoCommonDir(worktree_id) => {
3707 cx.emit(Event::WorktreeUpdatedRootRepoCommonDir(*worktree_id));
3708 }
3709 }
3710 }
3711
3712 fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
3713 let mut remotely_created_models = self.remotely_created_models.lock();
3714 if remotely_created_models.retain_count > 0 {
3715 remotely_created_models.worktrees.push(worktree.clone())
3716 }
3717 }
3718
3719 fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3720 if let Some(remote) = &self.remote_client {
3721 remote
3722 .read(cx)
3723 .proto_client()
3724 .send(proto::RemoveWorktree {
3725 worktree_id: id_to_remove.to_proto(),
3726 })
3727 .log_err();
3728 }
3729 }
3730
3731 fn on_buffer_event(
3732 &mut self,
3733 buffer: Entity<Buffer>,
3734 event: &BufferEvent,
3735 cx: &mut Context<Self>,
3736 ) -> Option<()> {
3737 if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
3738 self.request_buffer_diff_recalculation(&buffer, cx);
3739 }
3740
3741 if matches!(event, BufferEvent::Edited { .. }) {
3742 cx.emit(Event::BufferEdited);
3743 }
3744
3745 let buffer_id = buffer.read(cx).remote_id();
3746 match event {
3747 BufferEvent::ReloadNeeded => {
3748 if !self.is_via_collab() {
3749 self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
3750 .detach_and_log_err(cx);
3751 }
3752 }
3753 BufferEvent::Operation {
3754 operation,
3755 is_local: true,
3756 } => {
3757 let operation = language::proto::serialize_operation(operation);
3758
3759 if let Some(remote) = &self.remote_client {
3760 remote
3761 .read(cx)
3762 .proto_client()
3763 .send(proto::UpdateBuffer {
3764 project_id: 0,
3765 buffer_id: buffer_id.to_proto(),
3766 operations: vec![operation.clone()],
3767 })
3768 .ok();
3769 }
3770
3771 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
3772 buffer_id,
3773 operation,
3774 })
3775 .ok();
3776 }
3777
3778 _ => {}
3779 }
3780
3781 None
3782 }
3783
3784 fn on_image_event(
3785 &mut self,
3786 image: Entity<ImageItem>,
3787 event: &ImageItemEvent,
3788 cx: &mut Context<Self>,
3789 ) -> Option<()> {
3790 // TODO: handle image events from remote
3791 if let ImageItemEvent::ReloadNeeded = event
3792 && !self.is_via_collab()
3793 {
3794 self.reload_images([image].into_iter().collect(), cx)
3795 .detach_and_log_err(cx);
3796 }
3797
3798 None
3799 }
3800
3801 fn request_buffer_diff_recalculation(
3802 &mut self,
3803 buffer: &Entity<Buffer>,
3804 cx: &mut Context<Self>,
3805 ) {
3806 self.buffers_needing_diff.insert(buffer.downgrade());
3807 let first_insertion = self.buffers_needing_diff.len() == 1;
3808 let settings = ProjectSettings::get_global(cx);
3809 let delay = settings.git.gutter_debounce;
3810
3811 if delay == 0 {
3812 if first_insertion {
3813 let this = cx.weak_entity();
3814 cx.defer(move |cx| {
3815 if let Some(this) = this.upgrade() {
3816 this.update(cx, |this, cx| {
3817 this.recalculate_buffer_diffs(cx).detach();
3818 });
3819 }
3820 });
3821 }
3822 return;
3823 }
3824
3825 const MIN_DELAY: u64 = 50;
3826 let delay = delay.max(MIN_DELAY);
3827 let duration = Duration::from_millis(delay);
3828
3829 self.git_diff_debouncer
3830 .fire_new(duration, cx, move |this, cx| {
3831 this.recalculate_buffer_diffs(cx)
3832 });
3833 }
3834
3835 fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
3836 cx.spawn(async move |this, cx| {
3837 loop {
3838 let task = this
3839 .update(cx, |this, cx| {
3840 let buffers = this
3841 .buffers_needing_diff
3842 .drain()
3843 .filter_map(|buffer| buffer.upgrade())
3844 .collect::<Vec<_>>();
3845 if buffers.is_empty() {
3846 None
3847 } else {
3848 Some(this.git_store.update(cx, |git_store, cx| {
3849 git_store.recalculate_buffer_diffs(buffers, cx)
3850 }))
3851 }
3852 })
3853 .ok()
3854 .flatten();
3855
3856 if let Some(task) = task {
3857 task.await;
3858 } else {
3859 break;
3860 }
3861 }
3862 })
3863 }
3864
3865 pub fn set_language_for_buffer(
3866 &mut self,
3867 buffer: &Entity<Buffer>,
3868 new_language: Arc<Language>,
3869 cx: &mut Context<Self>,
3870 ) {
3871 self.lsp_store.update(cx, |lsp_store, cx| {
3872 lsp_store.set_language_for_buffer(buffer, new_language, cx)
3873 })
3874 }
3875
3876 pub fn restart_language_servers_for_buffers(
3877 &mut self,
3878 buffers: Vec<Entity<Buffer>>,
3879 only_restart_servers: HashSet<LanguageServerSelector>,
3880 cx: &mut Context<Self>,
3881 ) {
3882 self.lsp_store.update(cx, |lsp_store, cx| {
3883 lsp_store.restart_language_servers_for_buffers(buffers, only_restart_servers, cx)
3884 })
3885 }
3886
3887 pub fn stop_language_servers_for_buffers(
3888 &mut self,
3889 buffers: Vec<Entity<Buffer>>,
3890 also_restart_servers: HashSet<LanguageServerSelector>,
3891 cx: &mut Context<Self>,
3892 ) {
3893 self.lsp_store
3894 .update(cx, |lsp_store, cx| {
3895 lsp_store.stop_language_servers_for_buffers(buffers, also_restart_servers, cx)
3896 })
3897 .detach_and_log_err(cx);
3898 }
3899
3900 pub fn cancel_language_server_work_for_buffers(
3901 &mut self,
3902 buffers: impl IntoIterator<Item = Entity<Buffer>>,
3903 cx: &mut Context<Self>,
3904 ) {
3905 self.lsp_store.update(cx, |lsp_store, cx| {
3906 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3907 })
3908 }
3909
3910 pub fn cancel_language_server_work(
3911 &mut self,
3912 server_id: LanguageServerId,
3913 token_to_cancel: Option<ProgressToken>,
3914 cx: &mut Context<Self>,
3915 ) {
3916 self.lsp_store.update(cx, |lsp_store, cx| {
3917 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3918 })
3919 }
3920
3921 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3922 self.buffer_ordered_messages_tx
3923 .unbounded_send(message)
3924 .map_err(|e| anyhow!(e))
3925 }
3926
3927 pub fn available_toolchains(
3928 &self,
3929 path: ProjectPath,
3930 language_name: LanguageName,
3931 cx: &App,
3932 ) -> Task<Option<Toolchains>> {
3933 if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3934 cx.spawn(async move |cx| {
3935 toolchain_store
3936 .update(cx, |this, cx| this.list_toolchains(path, language_name, cx))
3937 .ok()?
3938 .await
3939 })
3940 } else {
3941 Task::ready(None)
3942 }
3943 }
3944
3945 pub async fn toolchain_metadata(
3946 languages: Arc<LanguageRegistry>,
3947 language_name: LanguageName,
3948 ) -> Option<ToolchainMetadata> {
3949 languages
3950 .language_for_name(language_name.as_ref())
3951 .await
3952 .ok()?
3953 .toolchain_lister()
3954 .map(|lister| lister.meta())
3955 }
3956
3957 pub fn add_toolchain(
3958 &self,
3959 toolchain: Toolchain,
3960 scope: ToolchainScope,
3961 cx: &mut Context<Self>,
3962 ) {
3963 maybe!({
3964 self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3965 this.add_toolchain(toolchain, scope, cx);
3966 });
3967 Some(())
3968 });
3969 }
3970
3971 pub fn remove_toolchain(
3972 &self,
3973 toolchain: Toolchain,
3974 scope: ToolchainScope,
3975 cx: &mut Context<Self>,
3976 ) {
3977 maybe!({
3978 self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3979 this.remove_toolchain(toolchain, scope, cx);
3980 });
3981 Some(())
3982 });
3983 }
3984
3985 pub fn user_toolchains(
3986 &self,
3987 cx: &App,
3988 ) -> Option<BTreeMap<ToolchainScope, IndexSet<Toolchain>>> {
3989 Some(self.toolchain_store.as_ref()?.read(cx).user_toolchains())
3990 }
3991
3992 pub fn resolve_toolchain(
3993 &self,
3994 path: PathBuf,
3995 language_name: LanguageName,
3996 cx: &App,
3997 ) -> Task<Result<Toolchain>> {
3998 if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3999 cx.spawn(async move |cx| {
4000 toolchain_store
4001 .update(cx, |this, cx| {
4002 this.resolve_toolchain(path, language_name, cx)
4003 })?
4004 .await
4005 })
4006 } else {
4007 Task::ready(Err(anyhow!("This project does not support toolchains")))
4008 }
4009 }
4010
4011 pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
4012 self.toolchain_store.clone()
4013 }
4014 pub fn activate_toolchain(
4015 &self,
4016 path: ProjectPath,
4017 toolchain: Toolchain,
4018 cx: &mut App,
4019 ) -> Task<Option<()>> {
4020 let Some(toolchain_store) = self.toolchain_store.clone() else {
4021 return Task::ready(None);
4022 };
4023 toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
4024 }
4025 pub fn active_toolchain(
4026 &self,
4027 path: ProjectPath,
4028 language_name: LanguageName,
4029 cx: &App,
4030 ) -> Task<Option<Toolchain>> {
4031 let Some(toolchain_store) = self.toolchain_store.clone() else {
4032 return Task::ready(None);
4033 };
4034 toolchain_store
4035 .read(cx)
4036 .active_toolchain(path, language_name, cx)
4037 }
4038 pub fn language_server_statuses<'a>(
4039 &'a self,
4040 cx: &'a App,
4041 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
4042 self.lsp_store.read(cx).language_server_statuses()
4043 }
4044
4045 pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
4046 self.lsp_store.read(cx).last_formatting_failure()
4047 }
4048
4049 pub fn reset_last_formatting_failure(&self, cx: &mut App) {
4050 self.lsp_store
4051 .update(cx, |store, _| store.reset_last_formatting_failure());
4052 }
4053
4054 pub fn reload_buffers(
4055 &self,
4056 buffers: HashSet<Entity<Buffer>>,
4057 push_to_history: bool,
4058 cx: &mut Context<Self>,
4059 ) -> Task<Result<ProjectTransaction>> {
4060 self.buffer_store.update(cx, |buffer_store, cx| {
4061 buffer_store.reload_buffers(buffers, push_to_history, cx)
4062 })
4063 }
4064
4065 pub fn reload_images(
4066 &self,
4067 images: HashSet<Entity<ImageItem>>,
4068 cx: &mut Context<Self>,
4069 ) -> Task<Result<()>> {
4070 self.image_store
4071 .update(cx, |image_store, cx| image_store.reload_images(images, cx))
4072 }
4073
4074 pub fn format(
4075 &mut self,
4076 buffers: HashSet<Entity<Buffer>>,
4077 target: LspFormatTarget,
4078 push_to_history: bool,
4079 trigger: lsp_store::FormatTrigger,
4080 cx: &mut Context<Project>,
4081 ) -> Task<anyhow::Result<ProjectTransaction>> {
4082 self.lsp_store.update(cx, |lsp_store, cx| {
4083 lsp_store.format(buffers, target, push_to_history, trigger, cx)
4084 })
4085 }
4086
4087 pub fn definitions<T: ToPointUtf16>(
4088 &mut self,
4089 buffer: &Entity<Buffer>,
4090 position: T,
4091 cx: &mut Context<Self>,
4092 ) -> Task<Result<Option<Vec<LocationLink>>>> {
4093 let position = position.to_point_utf16(buffer.read(cx));
4094 let guard = self.retain_remotely_created_models(cx);
4095 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4096 lsp_store.definitions(buffer, position, cx)
4097 });
4098 cx.background_spawn(async move {
4099 let result = task.await;
4100 drop(guard);
4101 result
4102 })
4103 }
4104
4105 pub fn declarations<T: ToPointUtf16>(
4106 &mut self,
4107 buffer: &Entity<Buffer>,
4108 position: T,
4109 cx: &mut Context<Self>,
4110 ) -> Task<Result<Option<Vec<LocationLink>>>> {
4111 let position = position.to_point_utf16(buffer.read(cx));
4112 let guard = self.retain_remotely_created_models(cx);
4113 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4114 lsp_store.declarations(buffer, position, cx)
4115 });
4116 cx.background_spawn(async move {
4117 let result = task.await;
4118 drop(guard);
4119 result
4120 })
4121 }
4122
4123 pub fn type_definitions<T: ToPointUtf16>(
4124 &mut self,
4125 buffer: &Entity<Buffer>,
4126 position: T,
4127 cx: &mut Context<Self>,
4128 ) -> Task<Result<Option<Vec<LocationLink>>>> {
4129 let position = position.to_point_utf16(buffer.read(cx));
4130 let guard = self.retain_remotely_created_models(cx);
4131 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4132 lsp_store.type_definitions(buffer, position, cx)
4133 });
4134 cx.background_spawn(async move {
4135 let result = task.await;
4136 drop(guard);
4137 result
4138 })
4139 }
4140
4141 pub fn implementations<T: ToPointUtf16>(
4142 &mut self,
4143 buffer: &Entity<Buffer>,
4144 position: T,
4145 cx: &mut Context<Self>,
4146 ) -> Task<Result<Option<Vec<LocationLink>>>> {
4147 let position = position.to_point_utf16(buffer.read(cx));
4148 let guard = self.retain_remotely_created_models(cx);
4149 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4150 lsp_store.implementations(buffer, position, cx)
4151 });
4152 cx.background_spawn(async move {
4153 let result = task.await;
4154 drop(guard);
4155 result
4156 })
4157 }
4158
4159 pub fn references<T: ToPointUtf16>(
4160 &mut self,
4161 buffer: &Entity<Buffer>,
4162 position: T,
4163 cx: &mut Context<Self>,
4164 ) -> Task<Result<Option<Vec<Location>>>> {
4165 let position = position.to_point_utf16(buffer.read(cx));
4166 let guard = self.retain_remotely_created_models(cx);
4167 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4168 lsp_store.references(buffer, position, cx)
4169 });
4170 cx.background_spawn(async move {
4171 let result = task.await;
4172 drop(guard);
4173 result
4174 })
4175 }
4176
4177 pub fn document_highlights<T: ToPointUtf16>(
4178 &mut self,
4179 buffer: &Entity<Buffer>,
4180 position: T,
4181 cx: &mut Context<Self>,
4182 ) -> Task<Result<Vec<DocumentHighlight>>> {
4183 let position = position.to_point_utf16(buffer.read(cx));
4184 self.request_lsp(
4185 buffer.clone(),
4186 LanguageServerToQuery::FirstCapable,
4187 GetDocumentHighlights { position },
4188 cx,
4189 )
4190 }
4191
4192 pub fn document_symbols(
4193 &mut self,
4194 buffer: &Entity<Buffer>,
4195 cx: &mut Context<Self>,
4196 ) -> Task<Result<Vec<DocumentSymbol>>> {
4197 self.request_lsp(
4198 buffer.clone(),
4199 LanguageServerToQuery::FirstCapable,
4200 GetDocumentSymbols,
4201 cx,
4202 )
4203 }
4204
4205 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
4206 self.lsp_store
4207 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
4208 }
4209
4210 pub fn open_buffer_for_symbol(
4211 &mut self,
4212 symbol: &Symbol,
4213 cx: &mut Context<Self>,
4214 ) -> Task<Result<Entity<Buffer>>> {
4215 self.lsp_store.update(cx, |lsp_store, cx| {
4216 lsp_store.open_buffer_for_symbol(symbol, cx)
4217 })
4218 }
4219
4220 pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
4221 let guard = self.retain_remotely_created_models(cx);
4222 let Some(remote) = self.remote_client.as_ref() else {
4223 return Task::ready(Err(anyhow!("not an ssh project")));
4224 };
4225
4226 let proto_client = remote.read(cx).proto_client();
4227
4228 cx.spawn(async move |project, cx| {
4229 let buffer = proto_client
4230 .request(proto::OpenServerSettings {
4231 project_id: REMOTE_SERVER_PROJECT_ID,
4232 })
4233 .await?;
4234
4235 let buffer = project
4236 .update(cx, |project, cx| {
4237 project.buffer_store.update(cx, |buffer_store, cx| {
4238 anyhow::Ok(
4239 buffer_store
4240 .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
4241 )
4242 })
4243 })??
4244 .await;
4245
4246 drop(guard);
4247 buffer
4248 })
4249 }
4250
4251 pub fn open_local_buffer_via_lsp(
4252 &mut self,
4253 abs_path: lsp::Uri,
4254 language_server_id: LanguageServerId,
4255 cx: &mut Context<Self>,
4256 ) -> Task<Result<Entity<Buffer>>> {
4257 self.lsp_store.update(cx, |lsp_store, cx| {
4258 lsp_store.open_local_buffer_via_lsp(abs_path, language_server_id, cx)
4259 })
4260 }
4261
4262 pub fn hover<T: ToPointUtf16>(
4263 &self,
4264 buffer: &Entity<Buffer>,
4265 position: T,
4266 cx: &mut Context<Self>,
4267 ) -> Task<Option<Vec<Hover>>> {
4268 let position = position.to_point_utf16(buffer.read(cx));
4269 self.lsp_store
4270 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
4271 }
4272
4273 pub fn linked_edits(
4274 &self,
4275 buffer: &Entity<Buffer>,
4276 position: Anchor,
4277 cx: &mut Context<Self>,
4278 ) -> Task<Result<Vec<Range<Anchor>>>> {
4279 self.lsp_store.update(cx, |lsp_store, cx| {
4280 lsp_store.linked_edits(buffer, position, cx)
4281 })
4282 }
4283
4284 pub fn completions<T: ToOffset + ToPointUtf16>(
4285 &self,
4286 buffer: &Entity<Buffer>,
4287 position: T,
4288 context: CompletionContext,
4289 cx: &mut Context<Self>,
4290 ) -> Task<Result<Vec<CompletionResponse>>> {
4291 let position = position.to_point_utf16(buffer.read(cx));
4292 self.lsp_store.update(cx, |lsp_store, cx| {
4293 lsp_store.completions(buffer, position, context, cx)
4294 })
4295 }
4296
4297 pub fn code_actions<T: Clone + ToOffset>(
4298 &mut self,
4299 buffer_handle: &Entity<Buffer>,
4300 range: Range<T>,
4301 kinds: Option<Vec<CodeActionKind>>,
4302 cx: &mut Context<Self>,
4303 ) -> Task<Result<Option<Vec<CodeAction>>>> {
4304 let buffer = buffer_handle.read(cx);
4305 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4306 self.lsp_store.update(cx, |lsp_store, cx| {
4307 lsp_store.code_actions(buffer_handle, range, kinds, cx)
4308 })
4309 }
4310
4311 pub fn code_lens_actions<T: Clone + ToOffset>(
4312 &mut self,
4313 buffer: &Entity<Buffer>,
4314 range: Range<T>,
4315 cx: &mut Context<Self>,
4316 ) -> Task<Result<Option<Vec<CodeAction>>>> {
4317 let snapshot = buffer.read(cx).snapshot();
4318 let range = range.to_point(&snapshot);
4319 let range_start = snapshot.anchor_before(range.start);
4320 let range_end = if range.start == range.end {
4321 range_start
4322 } else {
4323 snapshot.anchor_after(range.end)
4324 };
4325 let range = range_start..range_end;
4326 let code_lens_actions = self
4327 .lsp_store
4328 .update(cx, |lsp_store, cx| lsp_store.code_lens_actions(buffer, cx));
4329
4330 cx.background_spawn(async move {
4331 let mut code_lens_actions = code_lens_actions
4332 .await
4333 .map_err(|e| anyhow!("code lens fetch failed: {e:#}"))?;
4334 if let Some(code_lens_actions) = &mut code_lens_actions {
4335 code_lens_actions.retain(|code_lens_action| {
4336 range
4337 .start
4338 .cmp(&code_lens_action.range.start, &snapshot)
4339 .is_ge()
4340 && range
4341 .end
4342 .cmp(&code_lens_action.range.end, &snapshot)
4343 .is_le()
4344 });
4345 }
4346 Ok(code_lens_actions)
4347 })
4348 }
4349
4350 pub fn apply_code_action(
4351 &self,
4352 buffer_handle: Entity<Buffer>,
4353 action: CodeAction,
4354 push_to_history: bool,
4355 cx: &mut Context<Self>,
4356 ) -> Task<Result<ProjectTransaction>> {
4357 self.lsp_store.update(cx, |lsp_store, cx| {
4358 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
4359 })
4360 }
4361
4362 pub fn apply_code_action_kind(
4363 &self,
4364 buffers: HashSet<Entity<Buffer>>,
4365 kind: CodeActionKind,
4366 push_to_history: bool,
4367 cx: &mut Context<Self>,
4368 ) -> Task<Result<ProjectTransaction>> {
4369 self.lsp_store.update(cx, |lsp_store, cx| {
4370 lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
4371 })
4372 }
4373
4374 pub fn prepare_rename<T: ToPointUtf16>(
4375 &mut self,
4376 buffer: Entity<Buffer>,
4377 position: T,
4378 cx: &mut Context<Self>,
4379 ) -> Task<Result<PrepareRenameResponse>> {
4380 let position = position.to_point_utf16(buffer.read(cx));
4381 self.request_lsp(
4382 buffer,
4383 LanguageServerToQuery::FirstCapable,
4384 PrepareRename { position },
4385 cx,
4386 )
4387 }
4388
4389 pub fn perform_rename<T: ToPointUtf16>(
4390 &mut self,
4391 buffer: Entity<Buffer>,
4392 position: T,
4393 new_name: String,
4394 cx: &mut Context<Self>,
4395 ) -> Task<Result<ProjectTransaction>> {
4396 let push_to_history = true;
4397 let position = position.to_point_utf16(buffer.read(cx));
4398 self.request_lsp(
4399 buffer,
4400 LanguageServerToQuery::FirstCapable,
4401 PerformRename {
4402 position,
4403 new_name,
4404 push_to_history,
4405 },
4406 cx,
4407 )
4408 }
4409
4410 pub fn on_type_format<T: ToPointUtf16>(
4411 &mut self,
4412 buffer: Entity<Buffer>,
4413 position: T,
4414 trigger: String,
4415 push_to_history: bool,
4416 cx: &mut Context<Self>,
4417 ) -> Task<Result<Option<Transaction>>> {
4418 self.lsp_store.update(cx, |lsp_store, cx| {
4419 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
4420 })
4421 }
4422
4423 pub fn inline_values(
4424 &mut self,
4425 session: Entity<Session>,
4426 active_stack_frame: ActiveStackFrame,
4427 buffer_handle: Entity<Buffer>,
4428 range: Range<text::Anchor>,
4429 cx: &mut Context<Self>,
4430 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
4431 let snapshot = buffer_handle.read(cx).snapshot();
4432
4433 let captures =
4434 snapshot.debug_variables_query(Anchor::min_for_buffer(snapshot.remote_id())..range.end);
4435
4436 let row = snapshot
4437 .summary_for_anchor::<text::PointUtf16>(&range.end)
4438 .row as usize;
4439
4440 let inline_value_locations = provide_inline_values(captures, &snapshot, row);
4441
4442 let stack_frame_id = active_stack_frame.stack_frame_id;
4443 cx.spawn(async move |this, cx| {
4444 this.update(cx, |project, cx| {
4445 project.dap_store().update(cx, |dap_store, cx| {
4446 dap_store.resolve_inline_value_locations(
4447 session,
4448 stack_frame_id,
4449 buffer_handle,
4450 inline_value_locations,
4451 cx,
4452 )
4453 })
4454 })?
4455 .await
4456 })
4457 }
4458
4459 fn search_impl(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> SearchResultsHandle {
4460 let client: Option<(AnyProtoClient, _)> = if let Some(ssh_client) = &self.remote_client {
4461 Some((ssh_client.read(cx).proto_client(), 0))
4462 } else if let Some(remote_id) = self.remote_id() {
4463 self.is_local()
4464 .not()
4465 .then(|| (self.collab_client.clone().into(), remote_id))
4466 } else {
4467 None
4468 };
4469 let searcher = if query.is_opened_only() {
4470 project_search::Search::open_buffers_only(
4471 self.buffer_store.clone(),
4472 self.worktree_store.clone(),
4473 project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4474 )
4475 } else {
4476 match client {
4477 Some((client, remote_id)) => project_search::Search::remote(
4478 self.buffer_store.clone(),
4479 self.worktree_store.clone(),
4480 project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4481 (client, remote_id, self.remotely_created_models.clone()),
4482 ),
4483 None => project_search::Search::local(
4484 self.fs.clone(),
4485 self.buffer_store.clone(),
4486 self.worktree_store.clone(),
4487 project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4488 cx,
4489 ),
4490 }
4491 };
4492 searcher.into_handle(query, cx)
4493 }
4494
4495 pub fn search(
4496 &mut self,
4497 query: SearchQuery,
4498 cx: &mut Context<Self>,
4499 ) -> SearchResults<SearchResult> {
4500 self.search_impl(query, cx).results(cx)
4501 }
4502
4503 pub fn request_lsp<R: LspCommand>(
4504 &mut self,
4505 buffer_handle: Entity<Buffer>,
4506 server: LanguageServerToQuery,
4507 request: R,
4508 cx: &mut Context<Self>,
4509 ) -> Task<Result<R::Response>>
4510 where
4511 <R::LspRequest as lsp::request::Request>::Result: Send,
4512 <R::LspRequest as lsp::request::Request>::Params: Send,
4513 {
4514 let guard = self.retain_remotely_created_models(cx);
4515 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4516 lsp_store.request_lsp(buffer_handle, server, request, cx)
4517 });
4518 cx.background_spawn(async move {
4519 let result = task.await;
4520 drop(guard);
4521 result
4522 })
4523 }
4524
4525 /// Move a worktree to a new position in the worktree order.
4526 ///
4527 /// The worktree will moved to the opposite side of the destination worktree.
4528 ///
4529 /// # Example
4530 ///
4531 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4532 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4533 ///
4534 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4535 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4536 ///
4537 /// # Errors
4538 ///
4539 /// An error will be returned if the worktree or destination worktree are not found.
4540 pub fn move_worktree(
4541 &mut self,
4542 source: WorktreeId,
4543 destination: WorktreeId,
4544 cx: &mut Context<Self>,
4545 ) -> Result<()> {
4546 self.worktree_store.update(cx, |worktree_store, cx| {
4547 worktree_store.move_worktree(source, destination, cx)
4548 })
4549 }
4550
4551 /// 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.
4552 pub fn try_windows_path_to_wsl(
4553 &self,
4554 abs_path: &Path,
4555 cx: &App,
4556 ) -> impl Future<Output = Result<PathBuf>> + use<> {
4557 let fut = if cfg!(windows)
4558 && let (
4559 ProjectClientState::Local | ProjectClientState::Shared { .. },
4560 Some(remote_client),
4561 ) = (&self.client_state, &self.remote_client)
4562 && let RemoteConnectionOptions::Wsl(wsl) = remote_client.read(cx).connection_options()
4563 {
4564 Either::Left(wsl.abs_windows_path_to_wsl_path(abs_path))
4565 } else {
4566 Either::Right(abs_path.to_owned())
4567 };
4568 async move {
4569 match fut {
4570 Either::Left(fut) => fut.await.map(Into::into),
4571 Either::Right(path) => Ok(path),
4572 }
4573 }
4574 }
4575
4576 pub fn find_or_create_worktree(
4577 &mut self,
4578 abs_path: impl AsRef<Path>,
4579 visible: bool,
4580 cx: &mut Context<Self>,
4581 ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
4582 self.worktree_store.update(cx, |worktree_store, cx| {
4583 worktree_store.find_or_create_worktree(abs_path, visible, cx)
4584 })
4585 }
4586
4587 pub fn find_worktree(
4588 &self,
4589 abs_path: &Path,
4590 cx: &App,
4591 ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
4592 self.worktree_store.read(cx).find_worktree(abs_path, cx)
4593 }
4594
4595 pub fn is_shared(&self) -> bool {
4596 match &self.client_state {
4597 ProjectClientState::Shared { .. } => true,
4598 ProjectClientState::Local => false,
4599 ProjectClientState::Collab { .. } => true,
4600 }
4601 }
4602
4603 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4604 pub fn resolve_path_in_buffer(
4605 &self,
4606 path: &str,
4607 buffer: &Entity<Buffer>,
4608 cx: &mut Context<Self>,
4609 ) -> Task<Option<ResolvedPath>> {
4610 if util::paths::is_absolute(path, self.path_style(cx)) || path.starts_with("~") {
4611 self.resolve_abs_path(path, cx)
4612 } else {
4613 self.resolve_path_in_worktrees(path, buffer, cx)
4614 }
4615 }
4616
4617 pub fn resolve_abs_file_path(
4618 &self,
4619 path: &str,
4620 cx: &mut Context<Self>,
4621 ) -> Task<Option<ResolvedPath>> {
4622 let resolve_task = self.resolve_abs_path(path, cx);
4623 cx.background_spawn(async move {
4624 let resolved_path = resolve_task.await;
4625 resolved_path.filter(|path| path.is_file())
4626 })
4627 }
4628
4629 pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4630 if self.is_local() {
4631 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4632 let fs = self.fs.clone();
4633 cx.background_spawn(async move {
4634 let metadata = fs.metadata(&expanded).await.ok().flatten();
4635
4636 metadata.map(|metadata| ResolvedPath::AbsPath {
4637 path: expanded.to_string_lossy().into_owned(),
4638 is_dir: metadata.is_dir,
4639 })
4640 })
4641 } else if let Some(ssh_client) = self.remote_client.as_ref() {
4642 let request = ssh_client
4643 .read(cx)
4644 .proto_client()
4645 .request(proto::GetPathMetadata {
4646 project_id: REMOTE_SERVER_PROJECT_ID,
4647 path: path.into(),
4648 });
4649 cx.background_spawn(async move {
4650 let response = request.await.log_err()?;
4651 if response.exists {
4652 Some(ResolvedPath::AbsPath {
4653 path: response.path,
4654 is_dir: response.is_dir,
4655 })
4656 } else {
4657 None
4658 }
4659 })
4660 } else {
4661 Task::ready(None)
4662 }
4663 }
4664
4665 fn resolve_path_in_worktrees(
4666 &self,
4667 path: &str,
4668 buffer: &Entity<Buffer>,
4669 cx: &mut Context<Self>,
4670 ) -> Task<Option<ResolvedPath>> {
4671 let mut candidates = vec![];
4672 let path_style = self.path_style(cx);
4673 if let Ok(path) = RelPath::new(path.as_ref(), path_style) {
4674 candidates.push(path.into_arc());
4675 }
4676
4677 if let Some(file) = buffer.read(cx).file()
4678 && let Some(dir) = file.path().parent()
4679 {
4680 if let Some(joined) = path_style.join(&*dir.display(path_style), path)
4681 && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
4682 {
4683 candidates.push(joined.into_arc());
4684 }
4685 }
4686
4687 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4688 let worktrees_with_ids: Vec<_> = self
4689 .worktrees(cx)
4690 .map(|worktree| {
4691 let id = worktree.read(cx).id();
4692 (worktree, id)
4693 })
4694 .collect();
4695
4696 cx.spawn(async move |_, cx| {
4697 if let Some(buffer_worktree_id) = buffer_worktree_id
4698 && let Some((worktree, _)) = worktrees_with_ids
4699 .iter()
4700 .find(|(_, id)| *id == buffer_worktree_id)
4701 {
4702 for candidate in candidates.iter() {
4703 if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4704 return Some(path);
4705 }
4706 }
4707 }
4708 for (worktree, id) in worktrees_with_ids {
4709 if Some(id) == buffer_worktree_id {
4710 continue;
4711 }
4712 for candidate in candidates.iter() {
4713 if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4714 return Some(path);
4715 }
4716 }
4717 }
4718 None
4719 })
4720 }
4721
4722 fn resolve_path_in_worktree(
4723 worktree: &Entity<Worktree>,
4724 path: &RelPath,
4725 cx: &mut AsyncApp,
4726 ) -> Option<ResolvedPath> {
4727 worktree.read_with(cx, |worktree, _| {
4728 worktree.entry_for_path(path).map(|entry| {
4729 let project_path = ProjectPath {
4730 worktree_id: worktree.id(),
4731 path: entry.path.clone(),
4732 };
4733 ResolvedPath::ProjectPath {
4734 project_path,
4735 is_dir: entry.is_dir(),
4736 }
4737 })
4738 })
4739 }
4740
4741 pub fn list_directory(
4742 &self,
4743 query: String,
4744 cx: &mut Context<Self>,
4745 ) -> Task<Result<Vec<DirectoryItem>>> {
4746 if self.is_local() {
4747 DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4748 } else if let Some(session) = self.remote_client.as_ref() {
4749 let request = proto::ListRemoteDirectory {
4750 dev_server_id: REMOTE_SERVER_PROJECT_ID,
4751 path: query,
4752 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4753 };
4754
4755 let response = session.read(cx).proto_client().request(request);
4756 cx.background_spawn(async move {
4757 let proto::ListRemoteDirectoryResponse {
4758 entries,
4759 entry_info,
4760 } = response.await?;
4761 Ok(entries
4762 .into_iter()
4763 .zip(entry_info)
4764 .map(|(entry, info)| DirectoryItem {
4765 path: PathBuf::from(entry),
4766 is_dir: info.is_dir,
4767 })
4768 .collect())
4769 })
4770 } else {
4771 Task::ready(Err(anyhow!("cannot list directory in remote project")))
4772 }
4773 }
4774
4775 pub fn create_worktree(
4776 &mut self,
4777 abs_path: impl AsRef<Path>,
4778 visible: bool,
4779 cx: &mut Context<Self>,
4780 ) -> Task<Result<Entity<Worktree>>> {
4781 self.worktree_store.update(cx, |worktree_store, cx| {
4782 worktree_store.create_worktree(abs_path, visible, cx)
4783 })
4784 }
4785
4786 /// Returns a task that resolves when the given worktree's `Entity` is
4787 /// fully dropped (all strong references released), not merely when
4788 /// `remove_worktree` is called. `remove_worktree` drops the store's
4789 /// reference and emits `WorktreeRemoved`, but other code may still
4790 /// hold a strong handle — the worktree isn't safe to delete from
4791 /// disk until every handle is gone.
4792 ///
4793 /// We use `observe_release` on the specific entity rather than
4794 /// listening for `WorktreeReleased` events because it's simpler at
4795 /// the call site (one awaitable task, no subscription / channel /
4796 /// ID filtering).
4797 pub fn wait_for_worktree_release(
4798 &mut self,
4799 worktree_id: WorktreeId,
4800 cx: &mut Context<Self>,
4801 ) -> Task<Result<()>> {
4802 let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {
4803 return Task::ready(Ok(()));
4804 };
4805
4806 let (released_tx, released_rx) = futures::channel::oneshot::channel();
4807 let released_tx = std::sync::Arc::new(Mutex::new(Some(released_tx)));
4808 let release_subscription =
4809 cx.observe_release(&worktree, move |_project, _released_worktree, _cx| {
4810 if let Some(released_tx) = released_tx.lock().take() {
4811 let _ = released_tx.send(());
4812 }
4813 });
4814
4815 cx.spawn(async move |_project, _cx| {
4816 let _release_subscription = release_subscription;
4817 released_rx
4818 .await
4819 .map_err(|_| anyhow!("worktree release observer dropped before release"))?;
4820 Ok(())
4821 })
4822 }
4823
4824 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4825 self.worktree_store.update(cx, |worktree_store, cx| {
4826 worktree_store.remove_worktree(id_to_remove, cx);
4827 });
4828 }
4829
4830 pub fn remove_worktree_for_main_worktree_path(
4831 &mut self,
4832 path: impl AsRef<Path>,
4833 cx: &mut Context<Self>,
4834 ) {
4835 let path = path.as_ref();
4836 self.worktree_store.update(cx, |worktree_store, cx| {
4837 if let Some(worktree) = worktree_store.worktree_for_main_worktree_path(path, cx) {
4838 worktree_store.remove_worktree(worktree.read(cx).id(), cx);
4839 }
4840 });
4841 }
4842
4843 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4844 self.worktree_store.update(cx, |worktree_store, cx| {
4845 worktree_store.add(worktree, cx);
4846 });
4847 }
4848
4849 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4850 let new_active_entry = entry.and_then(|project_path| {
4851 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4852 let entry = worktree.read(cx).entry_for_path(&project_path.path)?;
4853 Some(entry.id)
4854 });
4855 if new_active_entry != self.active_entry {
4856 self.active_entry = new_active_entry;
4857 self.lsp_store.update(cx, |lsp_store, _| {
4858 lsp_store.set_active_entry(new_active_entry);
4859 });
4860 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4861 }
4862 }
4863
4864 pub fn language_servers_running_disk_based_diagnostics<'a>(
4865 &'a self,
4866 cx: &'a App,
4867 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4868 self.lsp_store
4869 .read(cx)
4870 .language_servers_running_disk_based_diagnostics()
4871 }
4872
4873 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4874 self.lsp_store
4875 .read(cx)
4876 .diagnostic_summary(include_ignored, cx)
4877 }
4878
4879 /// Returns a summary of the diagnostics for the provided project path only.
4880 pub fn diagnostic_summary_for_path(&self, path: &ProjectPath, cx: &App) -> DiagnosticSummary {
4881 self.lsp_store
4882 .read(cx)
4883 .diagnostic_summary_for_path(path, cx)
4884 }
4885
4886 pub fn diagnostic_summaries<'a>(
4887 &'a self,
4888 include_ignored: bool,
4889 cx: &'a App,
4890 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4891 self.lsp_store
4892 .read(cx)
4893 .diagnostic_summaries(include_ignored, cx)
4894 }
4895
4896 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4897 self.active_entry
4898 }
4899
4900 pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
4901 self.worktree_store.read(cx).entry_for_path(path, cx)
4902 }
4903
4904 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4905 let worktree = self.worktree_for_entry(entry_id, cx)?;
4906 let worktree = worktree.read(cx);
4907 let worktree_id = worktree.id();
4908 let path = worktree.entry_for_id(entry_id)?.path.clone();
4909 Some(ProjectPath { worktree_id, path })
4910 }
4911
4912 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4913 Some(
4914 self.worktree_for_id(project_path.worktree_id, cx)?
4915 .read(cx)
4916 .absolutize(&project_path.path),
4917 )
4918 }
4919
4920 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4921 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4922 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4923 /// the first visible worktree that has an entry for that relative path.
4924 ///
4925 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4926 /// root name from paths.
4927 ///
4928 /// # Arguments
4929 ///
4930 /// * `path` - An absolute path, or a full path that starts with a worktree root name, or a
4931 /// relative path within a visible worktree.
4932 /// * `cx` - A reference to the `AppContext`.
4933 ///
4934 /// # Returns
4935 ///
4936 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4937 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4938 let path_style = self.path_style(cx);
4939 let path = path.as_ref();
4940 let worktree_store = self.worktree_store.read(cx);
4941
4942 if is_absolute(&path.to_string_lossy(), path_style) {
4943 for worktree in worktree_store.visible_worktrees(cx) {
4944 let worktree_abs_path = worktree.read(cx).abs_path();
4945
4946 if let Ok(relative_path) = path.strip_prefix(worktree_abs_path)
4947 && let Ok(path) = RelPath::new(relative_path, path_style)
4948 {
4949 return Some(ProjectPath {
4950 worktree_id: worktree.read(cx).id(),
4951 path: path.into_arc(),
4952 });
4953 }
4954 }
4955 } else {
4956 for worktree in worktree_store.visible_worktrees(cx) {
4957 let worktree = worktree.read(cx);
4958 if let Ok(rel_path) = RelPath::new(path, path_style) {
4959 if let Some(entry) = worktree.entry_for_path(&rel_path) {
4960 return Some(ProjectPath {
4961 worktree_id: worktree.id(),
4962 path: entry.path.clone(),
4963 });
4964 }
4965 }
4966 }
4967
4968 for worktree in worktree_store.visible_worktrees(cx) {
4969 let worktree_root_name = worktree.read(cx).root_name();
4970 if let Ok(relative_path) = path.strip_prefix(worktree_root_name.as_std_path())
4971 && let Ok(path) = RelPath::new(relative_path, path_style)
4972 {
4973 return Some(ProjectPath {
4974 worktree_id: worktree.read(cx).id(),
4975 path: path.into_arc(),
4976 });
4977 }
4978 }
4979 }
4980
4981 None
4982 }
4983
4984 /// If there's only one visible worktree, returns the given worktree-relative path with no prefix.
4985 ///
4986 /// Otherwise, returns the full path for the project path (obtained by prefixing the worktree-relative path with the name of the worktree).
4987 pub fn short_full_path_for_project_path(
4988 &self,
4989 project_path: &ProjectPath,
4990 cx: &App,
4991 ) -> Option<String> {
4992 let path_style = self.path_style(cx);
4993 if self.visible_worktrees(cx).take(2).count() < 2 {
4994 return Some(project_path.path.display(path_style).to_string());
4995 }
4996 self.worktree_for_id(project_path.worktree_id, cx)
4997 .map(|worktree| {
4998 let worktree_name = worktree.read(cx).root_name();
4999 worktree_name
5000 .join(&project_path.path)
5001 .display(path_style)
5002 .to_string()
5003 })
5004 }
5005
5006 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
5007 self.worktree_store
5008 .read(cx)
5009 .project_path_for_absolute_path(abs_path, cx)
5010 }
5011
5012 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
5013 Some(
5014 self.worktree_for_id(project_path.worktree_id, cx)?
5015 .read(cx)
5016 .abs_path()
5017 .to_path_buf(),
5018 )
5019 }
5020
5021 pub fn blame_buffer(
5022 &self,
5023 buffer: &Entity<Buffer>,
5024 version: Option<clock::Global>,
5025 cx: &mut App,
5026 ) -> Task<Result<Option<Blame>>> {
5027 self.git_store.update(cx, |git_store, cx| {
5028 git_store.blame_buffer(buffer, version, cx)
5029 })
5030 }
5031
5032 pub fn get_permalink_to_line(
5033 &self,
5034 buffer: &Entity<Buffer>,
5035 selection: Range<u32>,
5036 cx: &mut App,
5037 ) -> Task<Result<url::Url>> {
5038 self.git_store.update(cx, |git_store, cx| {
5039 git_store.get_permalink_to_line(buffer, selection, cx)
5040 })
5041 }
5042
5043 // RPC message handlers
5044
5045 async fn handle_unshare_project(
5046 this: Entity<Self>,
5047 _: TypedEnvelope<proto::UnshareProject>,
5048 mut cx: AsyncApp,
5049 ) -> Result<()> {
5050 this.update(&mut cx, |this, cx| {
5051 if this.is_local() || this.is_via_remote_server() {
5052 this.unshare(cx)?;
5053 } else {
5054 this.disconnected_from_host(cx);
5055 }
5056 Ok(())
5057 })
5058 }
5059
5060 async fn handle_add_collaborator(
5061 this: Entity<Self>,
5062 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
5063 mut cx: AsyncApp,
5064 ) -> Result<()> {
5065 let collaborator = envelope
5066 .payload
5067 .collaborator
5068 .take()
5069 .context("empty collaborator")?;
5070
5071 let collaborator = Collaborator::from_proto(collaborator)?;
5072 this.update(&mut cx, |this, cx| {
5073 this.buffer_store.update(cx, |buffer_store, _| {
5074 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
5075 });
5076 this.breakpoint_store.read(cx).broadcast();
5077 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
5078 this.collaborators
5079 .insert(collaborator.peer_id, collaborator);
5080 });
5081
5082 Ok(())
5083 }
5084
5085 async fn handle_update_project_collaborator(
5086 this: Entity<Self>,
5087 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
5088 mut cx: AsyncApp,
5089 ) -> Result<()> {
5090 let old_peer_id = envelope
5091 .payload
5092 .old_peer_id
5093 .context("missing old peer id")?;
5094 let new_peer_id = envelope
5095 .payload
5096 .new_peer_id
5097 .context("missing new peer id")?;
5098 this.update(&mut cx, |this, cx| {
5099 let collaborator = this
5100 .collaborators
5101 .remove(&old_peer_id)
5102 .context("received UpdateProjectCollaborator for unknown peer")?;
5103 let is_host = collaborator.is_host;
5104 this.collaborators.insert(new_peer_id, collaborator);
5105
5106 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
5107 this.buffer_store.update(cx, |buffer_store, _| {
5108 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
5109 });
5110
5111 if is_host {
5112 this.buffer_store
5113 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
5114 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
5115 .unwrap();
5116 cx.emit(Event::HostReshared);
5117 }
5118
5119 cx.emit(Event::CollaboratorUpdated {
5120 old_peer_id,
5121 new_peer_id,
5122 });
5123 Ok(())
5124 })
5125 }
5126
5127 async fn handle_remove_collaborator(
5128 this: Entity<Self>,
5129 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
5130 mut cx: AsyncApp,
5131 ) -> Result<()> {
5132 this.update(&mut cx, |this, cx| {
5133 let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
5134 let replica_id = this
5135 .collaborators
5136 .remove(&peer_id)
5137 .with_context(|| format!("unknown peer {peer_id:?}"))?
5138 .replica_id;
5139 this.buffer_store.update(cx, |buffer_store, cx| {
5140 buffer_store.forget_shared_buffers_for(&peer_id);
5141 for buffer in buffer_store.buffers() {
5142 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
5143 }
5144 });
5145 this.git_store.update(cx, |git_store, _| {
5146 git_store.forget_shared_diffs_for(&peer_id);
5147 });
5148
5149 cx.emit(Event::CollaboratorLeft(peer_id));
5150 Ok(())
5151 })
5152 }
5153
5154 async fn handle_update_project(
5155 this: Entity<Self>,
5156 envelope: TypedEnvelope<proto::UpdateProject>,
5157 mut cx: AsyncApp,
5158 ) -> Result<()> {
5159 this.update(&mut cx, |this, cx| {
5160 // Don't handle messages that were sent before the response to us joining the project
5161 if envelope.message_id > this.join_project_response_message_id {
5162 cx.update_global::<SettingsStore, _>(|store, cx| {
5163 for worktree_metadata in &envelope.payload.worktrees {
5164 store
5165 .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
5166 .log_err();
5167 }
5168 });
5169
5170 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
5171 }
5172 Ok(())
5173 })
5174 }
5175
5176 async fn handle_toast(
5177 this: Entity<Self>,
5178 envelope: TypedEnvelope<proto::Toast>,
5179 mut cx: AsyncApp,
5180 ) -> Result<()> {
5181 this.update(&mut cx, |_, cx| {
5182 cx.emit(Event::Toast {
5183 notification_id: envelope.payload.notification_id.into(),
5184 message: envelope.payload.message,
5185 link: None,
5186 });
5187 Ok(())
5188 })
5189 }
5190
5191 async fn handle_language_server_prompt_request(
5192 this: Entity<Self>,
5193 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
5194 mut cx: AsyncApp,
5195 ) -> Result<proto::LanguageServerPromptResponse> {
5196 let (tx, rx) = smol::channel::bounded(1);
5197 let actions: Vec<_> = envelope
5198 .payload
5199 .actions
5200 .into_iter()
5201 .map(|action| MessageActionItem {
5202 title: action,
5203 properties: Default::default(),
5204 })
5205 .collect();
5206 this.update(&mut cx, |_, cx| {
5207 cx.emit(Event::LanguageServerPrompt(
5208 LanguageServerPromptRequest::new(
5209 proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
5210 envelope.payload.message,
5211 actions.clone(),
5212 envelope.payload.lsp_name,
5213 tx,
5214 ),
5215 ));
5216
5217 anyhow::Ok(())
5218 })?;
5219
5220 // We drop `this` to avoid holding a reference in this future for too
5221 // long.
5222 // If we keep the reference, we might not drop the `Project` early
5223 // enough when closing a window and it will only get releases on the
5224 // next `flush_effects()` call.
5225 drop(this);
5226
5227 let mut rx = pin!(rx);
5228 let answer = rx.next().await;
5229
5230 Ok(LanguageServerPromptResponse {
5231 action_response: answer.and_then(|answer| {
5232 actions
5233 .iter()
5234 .position(|action| *action == answer)
5235 .map(|index| index as u64)
5236 }),
5237 })
5238 }
5239
5240 async fn handle_hide_toast(
5241 this: Entity<Self>,
5242 envelope: TypedEnvelope<proto::HideToast>,
5243 mut cx: AsyncApp,
5244 ) -> Result<()> {
5245 this.update(&mut cx, |_, cx| {
5246 cx.emit(Event::HideToast {
5247 notification_id: envelope.payload.notification_id.into(),
5248 });
5249 Ok(())
5250 })
5251 }
5252
5253 // Collab sends UpdateWorktree protos as messages
5254 async fn handle_update_worktree(
5255 this: Entity<Self>,
5256 envelope: TypedEnvelope<proto::UpdateWorktree>,
5257 mut cx: AsyncApp,
5258 ) -> Result<()> {
5259 this.update(&mut cx, |project, cx| {
5260 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5261 if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
5262 worktree.update(cx, |worktree, _| {
5263 let worktree = worktree.as_remote_mut().unwrap();
5264 worktree.update_from_remote(envelope.payload);
5265 });
5266 }
5267 Ok(())
5268 })
5269 }
5270
5271 async fn handle_update_buffer_from_remote_server(
5272 this: Entity<Self>,
5273 envelope: TypedEnvelope<proto::UpdateBuffer>,
5274 cx: AsyncApp,
5275 ) -> Result<proto::Ack> {
5276 let buffer_store = this.read_with(&cx, |this, cx| {
5277 if let Some(remote_id) = this.remote_id() {
5278 let mut payload = envelope.payload.clone();
5279 payload.project_id = remote_id;
5280 cx.background_spawn(this.collab_client.request(payload))
5281 .detach_and_log_err(cx);
5282 }
5283 this.buffer_store.clone()
5284 });
5285 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
5286 }
5287
5288 async fn handle_trust_worktrees(
5289 this: Entity<Self>,
5290 envelope: TypedEnvelope<proto::TrustWorktrees>,
5291 mut cx: AsyncApp,
5292 ) -> Result<proto::Ack> {
5293 if this.read_with(&cx, |project, _| project.is_via_collab()) {
5294 return Ok(proto::Ack {});
5295 }
5296
5297 let trusted_worktrees = cx
5298 .update(|cx| TrustedWorktrees::try_get_global(cx))
5299 .context("missing trusted worktrees")?;
5300 trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
5301 trusted_worktrees.trust(
5302 &this.read(cx).worktree_store(),
5303 envelope
5304 .payload
5305 .trusted_paths
5306 .into_iter()
5307 .filter_map(|proto_path| PathTrust::from_proto(proto_path))
5308 .collect(),
5309 cx,
5310 );
5311 });
5312 Ok(proto::Ack {})
5313 }
5314
5315 async fn handle_restrict_worktrees(
5316 this: Entity<Self>,
5317 envelope: TypedEnvelope<proto::RestrictWorktrees>,
5318 mut cx: AsyncApp,
5319 ) -> Result<proto::Ack> {
5320 if this.read_with(&cx, |project, _| project.is_via_collab()) {
5321 return Ok(proto::Ack {});
5322 }
5323
5324 let trusted_worktrees = cx
5325 .update(|cx| TrustedWorktrees::try_get_global(cx))
5326 .context("missing trusted worktrees")?;
5327 trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
5328 let worktree_store = this.read(cx).worktree_store().downgrade();
5329 let restricted_paths = envelope
5330 .payload
5331 .worktree_ids
5332 .into_iter()
5333 .map(WorktreeId::from_proto)
5334 .map(PathTrust::Worktree)
5335 .collect::<HashSet<_>>();
5336 trusted_worktrees.restrict(worktree_store, restricted_paths, cx);
5337 });
5338 Ok(proto::Ack {})
5339 }
5340
5341 // Goes from host to client.
5342 async fn handle_find_search_candidates_chunk(
5343 this: Entity<Self>,
5344 envelope: TypedEnvelope<proto::FindSearchCandidatesChunk>,
5345 mut cx: AsyncApp,
5346 ) -> Result<proto::Ack> {
5347 let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
5348 BufferStore::handle_find_search_candidates_chunk(buffer_store, envelope, cx).await
5349 }
5350
5351 // Goes from client to host.
5352 async fn handle_find_search_candidates_cancel(
5353 this: Entity<Self>,
5354 envelope: TypedEnvelope<proto::FindSearchCandidatesCancelled>,
5355 mut cx: AsyncApp,
5356 ) -> Result<()> {
5357 let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
5358 BufferStore::handle_find_search_candidates_cancel(buffer_store, envelope, cx).await
5359 }
5360
5361 async fn handle_update_buffer(
5362 this: Entity<Self>,
5363 envelope: TypedEnvelope<proto::UpdateBuffer>,
5364 cx: AsyncApp,
5365 ) -> Result<proto::Ack> {
5366 let buffer_store = this.read_with(&cx, |this, cx| {
5367 if let Some(ssh) = &this.remote_client {
5368 let mut payload = envelope.payload.clone();
5369 payload.project_id = REMOTE_SERVER_PROJECT_ID;
5370 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
5371 .detach_and_log_err(cx);
5372 }
5373 this.buffer_store.clone()
5374 });
5375 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
5376 }
5377
5378 fn retain_remotely_created_models(
5379 &mut self,
5380 cx: &mut Context<Self>,
5381 ) -> RemotelyCreatedModelGuard {
5382 Self::retain_remotely_created_models_impl(
5383 &self.remotely_created_models,
5384 &self.buffer_store,
5385 &self.worktree_store,
5386 cx,
5387 )
5388 }
5389
5390 fn retain_remotely_created_models_impl(
5391 models: &Arc<Mutex<RemotelyCreatedModels>>,
5392 buffer_store: &Entity<BufferStore>,
5393 worktree_store: &Entity<WorktreeStore>,
5394 cx: &mut App,
5395 ) -> RemotelyCreatedModelGuard {
5396 {
5397 let mut remotely_create_models = models.lock();
5398 if remotely_create_models.retain_count == 0 {
5399 remotely_create_models.buffers = buffer_store.read(cx).buffers().collect();
5400 remotely_create_models.worktrees = worktree_store.read(cx).worktrees().collect();
5401 }
5402 remotely_create_models.retain_count += 1;
5403 }
5404 RemotelyCreatedModelGuard {
5405 remote_models: Arc::downgrade(&models),
5406 }
5407 }
5408
5409 async fn handle_create_buffer_for_peer(
5410 this: Entity<Self>,
5411 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5412 mut cx: AsyncApp,
5413 ) -> Result<()> {
5414 this.update(&mut cx, |this, cx| {
5415 this.buffer_store.update(cx, |buffer_store, cx| {
5416 buffer_store.handle_create_buffer_for_peer(
5417 envelope,
5418 this.replica_id(),
5419 this.capability(),
5420 cx,
5421 )
5422 })
5423 })
5424 }
5425
5426 async fn handle_toggle_lsp_logs(
5427 project: Entity<Self>,
5428 envelope: TypedEnvelope<proto::ToggleLspLogs>,
5429 mut cx: AsyncApp,
5430 ) -> Result<()> {
5431 let toggled_log_kind =
5432 match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
5433 .context("invalid log type")?
5434 {
5435 proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
5436 proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
5437 proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
5438 };
5439 project.update(&mut cx, |_, cx| {
5440 cx.emit(Event::ToggleLspLogs {
5441 server_id: LanguageServerId::from_proto(envelope.payload.server_id),
5442 enabled: envelope.payload.enabled,
5443 toggled_log_kind,
5444 })
5445 });
5446 Ok(())
5447 }
5448
5449 async fn handle_synchronize_buffers(
5450 this: Entity<Self>,
5451 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5452 mut cx: AsyncApp,
5453 ) -> Result<proto::SynchronizeBuffersResponse> {
5454 let response = this.update(&mut cx, |this, cx| {
5455 let client = this.collab_client.clone();
5456 this.buffer_store.update(cx, |this, cx| {
5457 this.handle_synchronize_buffers(envelope, cx, client)
5458 })
5459 })?;
5460
5461 Ok(response)
5462 }
5463
5464 // Goes from client to host.
5465 async fn handle_search_candidate_buffers(
5466 this: Entity<Self>,
5467 envelope: TypedEnvelope<proto::FindSearchCandidates>,
5468 mut cx: AsyncApp,
5469 ) -> Result<proto::Ack> {
5470 let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
5471 let message = envelope.payload;
5472 let project_id = message.project_id;
5473 let path_style = this.read_with(&cx, |this, cx| this.path_style(cx));
5474 let query =
5475 SearchQuery::from_proto(message.query.context("missing query field")?, path_style)?;
5476
5477 let handle = message.handle;
5478 let buffer_store = this.read_with(&cx, |this, _| this.buffer_store().clone());
5479 let client = this.read_with(&cx, |this, _| this.client());
5480 let task = cx.spawn(async move |cx| {
5481 let results = this.update(cx, |this, cx| {
5482 this.search_impl(query, cx).matching_buffers(cx)
5483 });
5484 let (batcher, batches) = project_search::AdaptiveBatcher::new(cx.background_executor());
5485 let mut new_matches = Box::pin(results.rx);
5486
5487 let sender_task = cx.background_executor().spawn({
5488 let client = client.clone();
5489 async move {
5490 let mut batches = std::pin::pin!(batches);
5491 while let Some(buffer_ids) = batches.next().await {
5492 client
5493 .request(proto::FindSearchCandidatesChunk {
5494 handle,
5495 peer_id: Some(peer_id),
5496 project_id,
5497 variant: Some(
5498 proto::find_search_candidates_chunk::Variant::Matches(
5499 proto::FindSearchCandidatesMatches { buffer_ids },
5500 ),
5501 ),
5502 })
5503 .await?;
5504 }
5505 anyhow::Ok(())
5506 }
5507 });
5508
5509 while let Some(buffer) = new_matches.next().await {
5510 let buffer_id = this.update(cx, |this, cx| {
5511 this.create_buffer_for_peer(&buffer, peer_id, cx).to_proto()
5512 });
5513 batcher.push(buffer_id).await;
5514 }
5515 batcher.flush().await;
5516
5517 sender_task.await?;
5518
5519 let _ = client
5520 .request(proto::FindSearchCandidatesChunk {
5521 handle,
5522 peer_id: Some(peer_id),
5523 project_id,
5524 variant: Some(proto::find_search_candidates_chunk::Variant::Done(
5525 proto::FindSearchCandidatesDone {},
5526 )),
5527 })
5528 .await?;
5529 anyhow::Ok(())
5530 });
5531 buffer_store.update(&mut cx, |this, _| {
5532 this.register_ongoing_project_search((peer_id, handle), task);
5533 });
5534
5535 Ok(proto::Ack {})
5536 }
5537
5538 async fn handle_open_buffer_by_id(
5539 this: Entity<Self>,
5540 envelope: TypedEnvelope<proto::OpenBufferById>,
5541 mut cx: AsyncApp,
5542 ) -> Result<proto::OpenBufferResponse> {
5543 let peer_id = envelope.original_sender_id()?;
5544 let buffer_id = BufferId::new(envelope.payload.id)?;
5545 let buffer = this
5546 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))
5547 .await?;
5548 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5549 }
5550
5551 async fn handle_open_buffer_by_path(
5552 this: Entity<Self>,
5553 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5554 mut cx: AsyncApp,
5555 ) -> Result<proto::OpenBufferResponse> {
5556 let peer_id = envelope.original_sender_id()?;
5557 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5558 let path = RelPath::from_proto(&envelope.payload.path)?;
5559 let open_buffer = this
5560 .update(&mut cx, |this, cx| {
5561 this.open_buffer(ProjectPath { worktree_id, path }, cx)
5562 })
5563 .await?;
5564 Project::respond_to_open_buffer_request(this, open_buffer, peer_id, &mut cx)
5565 }
5566
5567 async fn handle_open_new_buffer(
5568 this: Entity<Self>,
5569 envelope: TypedEnvelope<proto::OpenNewBuffer>,
5570 mut cx: AsyncApp,
5571 ) -> Result<proto::OpenBufferResponse> {
5572 let buffer = this
5573 .update(&mut cx, |this, cx| this.create_buffer(None, true, cx))
5574 .await?;
5575 let peer_id = envelope.original_sender_id()?;
5576
5577 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5578 }
5579
5580 fn respond_to_open_buffer_request(
5581 this: Entity<Self>,
5582 buffer: Entity<Buffer>,
5583 peer_id: proto::PeerId,
5584 cx: &mut AsyncApp,
5585 ) -> Result<proto::OpenBufferResponse> {
5586 this.update(cx, |this, cx| {
5587 let is_private = buffer
5588 .read(cx)
5589 .file()
5590 .map(|f| f.is_private())
5591 .unwrap_or_default();
5592 anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
5593 Ok(proto::OpenBufferResponse {
5594 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
5595 })
5596 })
5597 }
5598
5599 fn create_buffer_for_peer(
5600 &mut self,
5601 buffer: &Entity<Buffer>,
5602 peer_id: proto::PeerId,
5603 cx: &mut App,
5604 ) -> BufferId {
5605 self.buffer_store
5606 .update(cx, |buffer_store, cx| {
5607 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
5608 })
5609 .detach_and_log_err(cx);
5610 buffer.read(cx).remote_id()
5611 }
5612
5613 async fn handle_create_image_for_peer(
5614 this: Entity<Self>,
5615 envelope: TypedEnvelope<proto::CreateImageForPeer>,
5616 mut cx: AsyncApp,
5617 ) -> Result<()> {
5618 this.update(&mut cx, |this, cx| {
5619 this.image_store.update(cx, |image_store, cx| {
5620 image_store.handle_create_image_for_peer(envelope, cx)
5621 })
5622 })
5623 }
5624
5625 async fn handle_create_file_for_peer(
5626 this: Entity<Self>,
5627 envelope: TypedEnvelope<proto::CreateFileForPeer>,
5628 mut cx: AsyncApp,
5629 ) -> Result<()> {
5630 use proto::create_file_for_peer::Variant;
5631 log::debug!("handle_create_file_for_peer: received message");
5632
5633 let downloading_files: Arc<Mutex<HashMap<(WorktreeId, String), DownloadingFile>>> =
5634 this.update(&mut cx, |this, _| this.downloading_files.clone());
5635
5636 match &envelope.payload.variant {
5637 Some(Variant::State(state)) => {
5638 log::debug!(
5639 "handle_create_file_for_peer: got State: id={}, content_size={}",
5640 state.id,
5641 state.content_size
5642 );
5643
5644 // Extract worktree_id and path from the File field
5645 if let Some(ref file) = state.file {
5646 let worktree_id = WorktreeId::from_proto(file.worktree_id);
5647 let path = file.path.clone();
5648 let key = (worktree_id, path);
5649 log::debug!("handle_create_file_for_peer: looking up key={:?}", key);
5650
5651 let empty_file_destination: Option<PathBuf> = {
5652 let mut files = downloading_files.lock();
5653 log::trace!(
5654 "handle_create_file_for_peer: current downloading_files keys: {:?}",
5655 files.keys().collect::<Vec<_>>()
5656 );
5657
5658 if let Some(file_entry) = files.get_mut(&key) {
5659 file_entry.total_size = state.content_size;
5660 file_entry.file_id = Some(state.id);
5661 log::debug!(
5662 "handle_create_file_for_peer: updated file entry: total_size={}, file_id={}",
5663 state.content_size,
5664 state.id
5665 );
5666 } else {
5667 log::warn!(
5668 "handle_create_file_for_peer: key={:?} not found in downloading_files",
5669 key
5670 );
5671 }
5672
5673 if state.content_size == 0 {
5674 // No chunks will arrive for an empty file; write it now.
5675 files.remove(&key).map(|entry| entry.destination_path)
5676 } else {
5677 None
5678 }
5679 };
5680
5681 if let Some(destination) = empty_file_destination {
5682 log::debug!(
5683 "handle_create_file_for_peer: writing empty file to {:?}",
5684 destination
5685 );
5686 match smol::fs::write(&destination, &[] as &[u8]).await {
5687 Ok(_) => log::info!(
5688 "handle_create_file_for_peer: successfully wrote file to {:?}",
5689 destination
5690 ),
5691 Err(e) => log::error!(
5692 "handle_create_file_for_peer: failed to write empty file: {:?}",
5693 e
5694 ),
5695 }
5696 }
5697 } else {
5698 log::warn!("handle_create_file_for_peer: State has no file field");
5699 }
5700 }
5701 Some(Variant::Chunk(chunk)) => {
5702 log::debug!(
5703 "handle_create_file_for_peer: got Chunk: file_id={}, data_len={}",
5704 chunk.file_id,
5705 chunk.data.len()
5706 );
5707
5708 // Extract data while holding the lock, then release it before await
5709 let (key_to_remove, write_info): (
5710 Option<(WorktreeId, String)>,
5711 Option<(PathBuf, Vec<u8>)>,
5712 ) = {
5713 let mut files = downloading_files.lock();
5714 let mut found_key: Option<(WorktreeId, String)> = None;
5715 let mut write_data: Option<(PathBuf, Vec<u8>)> = None;
5716
5717 for (key, file_entry) in files.iter_mut() {
5718 if file_entry.file_id == Some(chunk.file_id) {
5719 file_entry.chunks.extend_from_slice(&chunk.data);
5720 log::debug!(
5721 "handle_create_file_for_peer: accumulated {} bytes, total_size={}",
5722 file_entry.chunks.len(),
5723 file_entry.total_size
5724 );
5725
5726 if file_entry.chunks.len() as u64 >= file_entry.total_size
5727 && file_entry.total_size > 0
5728 {
5729 let destination = file_entry.destination_path.clone();
5730 let content = std::mem::take(&mut file_entry.chunks);
5731 found_key = Some(key.clone());
5732 write_data = Some((destination, content));
5733 }
5734 break;
5735 }
5736 }
5737 (found_key, write_data)
5738 }; // MutexGuard is dropped here
5739
5740 // Perform the async write outside the lock
5741 if let Some((destination, content)) = write_info {
5742 log::debug!(
5743 "handle_create_file_for_peer: writing {} bytes to {:?}",
5744 content.len(),
5745 destination
5746 );
5747 match smol::fs::write(&destination, &content).await {
5748 Ok(_) => log::info!(
5749 "handle_create_file_for_peer: successfully wrote file to {:?}",
5750 destination
5751 ),
5752 Err(e) => log::error!(
5753 "handle_create_file_for_peer: failed to write file: {:?}",
5754 e
5755 ),
5756 }
5757 }
5758
5759 // Remove the completed entry
5760 if let Some(key) = key_to_remove {
5761 downloading_files.lock().remove(&key);
5762 log::debug!("handle_create_file_for_peer: removed completed download entry");
5763 }
5764 }
5765 None => {
5766 log::warn!("handle_create_file_for_peer: got None variant");
5767 }
5768 }
5769
5770 Ok(())
5771 }
5772
5773 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
5774 let project_id = match self.client_state {
5775 ProjectClientState::Collab {
5776 sharing_has_stopped,
5777 remote_id,
5778 ..
5779 } => {
5780 if sharing_has_stopped {
5781 return Task::ready(Err(anyhow!(
5782 "can't synchronize remote buffers on a readonly project"
5783 )));
5784 } else {
5785 remote_id
5786 }
5787 }
5788 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
5789 return Task::ready(Err(anyhow!(
5790 "can't synchronize remote buffers on a local project"
5791 )));
5792 }
5793 };
5794
5795 let client = self.collab_client.clone();
5796 cx.spawn(async move |this, cx| {
5797 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
5798 this.buffer_store.read(cx).buffer_version_info(cx)
5799 })?;
5800 let response = client
5801 .request(proto::SynchronizeBuffers {
5802 project_id,
5803 buffers,
5804 })
5805 .await?;
5806
5807 let send_updates_for_buffers = this.update(cx, |this, cx| {
5808 response
5809 .buffers
5810 .into_iter()
5811 .map(|buffer| {
5812 let client = client.clone();
5813 let buffer_id = match BufferId::new(buffer.id) {
5814 Ok(id) => id,
5815 Err(e) => {
5816 return Task::ready(Err(e));
5817 }
5818 };
5819 let remote_version = language::proto::deserialize_version(&buffer.version);
5820 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5821 let operations =
5822 buffer.read(cx).serialize_ops(Some(remote_version), cx);
5823 cx.background_spawn(async move {
5824 let operations = operations.await;
5825 for chunk in split_operations(operations) {
5826 client
5827 .request(proto::UpdateBuffer {
5828 project_id,
5829 buffer_id: buffer_id.into(),
5830 operations: chunk,
5831 })
5832 .await?;
5833 }
5834 anyhow::Ok(())
5835 })
5836 } else {
5837 Task::ready(Ok(()))
5838 }
5839 })
5840 .collect::<Vec<_>>()
5841 })?;
5842
5843 // Any incomplete buffers have open requests waiting. Request that the host sends
5844 // creates these buffers for us again to unblock any waiting futures.
5845 for id in incomplete_buffer_ids {
5846 cx.background_spawn(client.request(proto::OpenBufferById {
5847 project_id,
5848 id: id.into(),
5849 }))
5850 .detach();
5851 }
5852
5853 futures::future::join_all(send_updates_for_buffers)
5854 .await
5855 .into_iter()
5856 .collect()
5857 })
5858 }
5859
5860 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
5861 self.worktree_store.read(cx).worktree_metadata_protos(cx)
5862 }
5863
5864 /// Iterator of all open buffers that have unsaved changes
5865 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
5866 self.buffer_store.read(cx).buffers().filter_map(|buf| {
5867 let buf = buf.read(cx);
5868 if buf.is_dirty() {
5869 buf.project_path(cx)
5870 } else {
5871 None
5872 }
5873 })
5874 }
5875
5876 fn set_worktrees_from_proto(
5877 &mut self,
5878 worktrees: Vec<proto::WorktreeMetadata>,
5879 cx: &mut Context<Project>,
5880 ) -> Result<()> {
5881 self.worktree_store.update(cx, |worktree_store, cx| {
5882 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
5883 })
5884 }
5885
5886 fn set_collaborators_from_proto(
5887 &mut self,
5888 messages: Vec<proto::Collaborator>,
5889 cx: &mut Context<Self>,
5890 ) -> Result<()> {
5891 let mut collaborators = HashMap::default();
5892 for message in messages {
5893 let collaborator = Collaborator::from_proto(message)?;
5894 collaborators.insert(collaborator.peer_id, collaborator);
5895 }
5896 for old_peer_id in self.collaborators.keys() {
5897 if !collaborators.contains_key(old_peer_id) {
5898 cx.emit(Event::CollaboratorLeft(*old_peer_id));
5899 }
5900 }
5901 self.collaborators = collaborators;
5902 Ok(())
5903 }
5904
5905 pub fn supplementary_language_servers<'a>(
5906 &'a self,
5907 cx: &'a App,
5908 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
5909 self.lsp_store.read(cx).supplementary_language_servers()
5910 }
5911
5912 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
5913 let Some(language) = buffer.language().cloned() else {
5914 return false;
5915 };
5916 self.lsp_store.update(cx, |lsp_store, _| {
5917 let relevant_language_servers = lsp_store
5918 .languages
5919 .lsp_adapters(&language.name())
5920 .into_iter()
5921 .map(|lsp_adapter| lsp_adapter.name())
5922 .collect::<HashSet<_>>();
5923 lsp_store
5924 .language_server_statuses()
5925 .filter_map(|(server_id, server_status)| {
5926 relevant_language_servers
5927 .contains(&server_status.name)
5928 .then_some(server_id)
5929 })
5930 .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5931 .any(InlayHints::check_capabilities)
5932 })
5933 }
5934
5935 pub fn any_language_server_supports_semantic_tokens(
5936 &self,
5937 buffer: &Buffer,
5938 cx: &mut App,
5939 ) -> bool {
5940 let Some(language) = buffer.language().cloned() else {
5941 return false;
5942 };
5943 let lsp_store = self.lsp_store.read(cx);
5944 let relevant_language_servers = lsp_store
5945 .languages
5946 .lsp_adapters(&language.name())
5947 .into_iter()
5948 .map(|lsp_adapter| lsp_adapter.name())
5949 .collect::<HashSet<_>>();
5950 lsp_store
5951 .language_server_statuses()
5952 .filter_map(|(server_id, server_status)| {
5953 relevant_language_servers
5954 .contains(&server_status.name)
5955 .then_some(server_id)
5956 })
5957 .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5958 .any(|capabilities| capabilities.semantic_tokens_provider.is_some())
5959 }
5960
5961 pub fn language_server_id_for_name(
5962 &self,
5963 buffer: &Buffer,
5964 name: &LanguageServerName,
5965 cx: &App,
5966 ) -> Option<LanguageServerId> {
5967 let language = buffer.language()?;
5968 let relevant_language_servers = self
5969 .languages
5970 .lsp_adapters(&language.name())
5971 .into_iter()
5972 .map(|lsp_adapter| lsp_adapter.name())
5973 .collect::<HashSet<_>>();
5974 if !relevant_language_servers.contains(name) {
5975 return None;
5976 }
5977 self.language_server_statuses(cx)
5978 .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
5979 .find_map(|(server_id, server_status)| {
5980 if &server_status.name == name {
5981 Some(server_id)
5982 } else {
5983 None
5984 }
5985 })
5986 }
5987
5988 #[cfg(feature = "test-support")]
5989 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
5990 self.lsp_store.update(cx, |this, cx| {
5991 this.running_language_servers_for_local_buffer(buffer, cx)
5992 .next()
5993 .is_some()
5994 })
5995 }
5996
5997 pub fn git_init(
5998 &self,
5999 path: Arc<Path>,
6000 fallback_branch_name: String,
6001 cx: &App,
6002 ) -> Task<Result<()>> {
6003 self.git_store
6004 .read(cx)
6005 .git_init(path, fallback_branch_name, cx)
6006 }
6007
6008 pub fn buffer_store(&self) -> &Entity<BufferStore> {
6009 &self.buffer_store
6010 }
6011
6012 pub fn git_store(&self) -> &Entity<GitStore> {
6013 &self.git_store
6014 }
6015
6016 pub fn agent_server_store(&self) -> &Entity<AgentServerStore> {
6017 &self.agent_server_store
6018 }
6019
6020 #[cfg(feature = "test-support")]
6021 pub fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
6022 use futures::future::join_all;
6023 cx.spawn(async move |this, cx| {
6024 let scans_complete = this
6025 .read_with(cx, |this, cx| {
6026 this.worktrees(cx)
6027 .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
6028 .collect::<Vec<_>>()
6029 })
6030 .unwrap();
6031 join_all(scans_complete).await;
6032 let barriers = this
6033 .update(cx, |this, cx| {
6034 let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
6035 repos
6036 .into_iter()
6037 .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
6038 .collect::<Vec<_>>()
6039 })
6040 .unwrap();
6041 join_all(barriers).await;
6042 })
6043 }
6044
6045 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
6046 self.git_store.read(cx).active_repository()
6047 }
6048
6049 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
6050 self.git_store.read(cx).repositories()
6051 }
6052
6053 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
6054 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
6055 }
6056
6057 pub fn set_agent_location(
6058 &mut self,
6059 new_location: Option<AgentLocation>,
6060 cx: &mut Context<Self>,
6061 ) {
6062 if let Some(old_location) = self.agent_location.as_ref() {
6063 old_location
6064 .buffer
6065 .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
6066 .ok();
6067 }
6068
6069 if let Some(location) = new_location.as_ref() {
6070 location
6071 .buffer
6072 .update(cx, |buffer, cx| {
6073 buffer.set_agent_selections(
6074 Arc::from([language::Selection {
6075 id: 0,
6076 start: location.position,
6077 end: location.position,
6078 reversed: false,
6079 goal: language::SelectionGoal::None,
6080 }]),
6081 false,
6082 CursorShape::Hollow,
6083 cx,
6084 )
6085 })
6086 .ok();
6087 }
6088
6089 self.agent_location = new_location;
6090 cx.emit(Event::AgentLocationChanged);
6091 }
6092
6093 pub fn agent_location(&self) -> Option<AgentLocation> {
6094 self.agent_location.clone()
6095 }
6096
6097 pub fn path_style(&self, cx: &App) -> PathStyle {
6098 self.worktree_store.read(cx).path_style()
6099 }
6100
6101 pub fn contains_local_settings_file(
6102 &self,
6103 worktree_id: WorktreeId,
6104 rel_path: &RelPath,
6105 cx: &App,
6106 ) -> bool {
6107 self.worktree_for_id(worktree_id, cx)
6108 .map_or(false, |worktree| {
6109 worktree.read(cx).entry_for_path(rel_path).is_some()
6110 })
6111 }
6112}
6113
6114/// Identifies a project group by a set of paths the workspaces in this group
6115/// have.
6116///
6117/// Paths are mapped to their main worktree path first so we can group
6118/// workspaces by main repos.
6119/// Stable identity for a project group. Unlike `ProjectGroupKey` (which is
6120/// derived from filesystem paths and changes when folders are added/removed),
6121/// a `ProjectGroupId` is assigned once when the group is created and never
6122/// changes.
6123#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, serde::Serialize, serde::Deserialize)]
6124pub struct ProjectGroupId(uuid::Uuid);
6125
6126impl ProjectGroupId {
6127 pub fn new() -> Self {
6128 Self(uuid::Uuid::new_v4())
6129 }
6130}
6131
6132/// A computed descriptor of a project's worktree paths + optional remote host.
6133/// Used for matching workspaces to existing groups. Equality is path-based.
6134#[derive(PartialEq, Eq, Hash, Clone, Debug)]
6135pub struct ProjectGroupKey {
6136 /// The paths of the main worktrees for this project group.
6137 paths: PathList,
6138 host: Option<RemoteConnectionOptions>,
6139}
6140
6141impl ProjectGroupKey {
6142 /// Creates a new `ProjectGroupKey` with the given path list.
6143 ///
6144 /// The path list should point to the git main worktree paths for a project.
6145 pub fn new(host: Option<RemoteConnectionOptions>, paths: PathList) -> Self {
6146 Self { paths, host }
6147 }
6148
6149 pub fn path_list(&self) -> &PathList {
6150 &self.paths
6151 }
6152
6153 pub fn display_name(
6154 &self,
6155 path_detail_map: &std::collections::HashMap<PathBuf, usize>,
6156 ) -> SharedString {
6157 let mut names = Vec::with_capacity(self.paths.paths().len());
6158 for abs_path in self.paths.paths() {
6159 let detail = path_detail_map.get(abs_path).copied().unwrap_or(0);
6160 let suffix = path_suffix(abs_path, detail);
6161 if !suffix.is_empty() {
6162 names.push(suffix);
6163 }
6164 }
6165 if names.is_empty() {
6166 "Empty Workspace".into()
6167 } else {
6168 names.join(", ").into()
6169 }
6170 }
6171
6172 pub fn host(&self) -> Option<RemoteConnectionOptions> {
6173 self.host.clone()
6174 }
6175}
6176
6177pub fn path_suffix(path: &Path, detail: usize) -> String {
6178 let mut components: Vec<_> = path
6179 .components()
6180 .rev()
6181 .filter_map(|component| match component {
6182 std::path::Component::Normal(s) => Some(s.to_string_lossy()),
6183 _ => None,
6184 })
6185 .take(detail + 1)
6186 .collect();
6187 components.reverse();
6188 components.join("/")
6189}
6190
6191pub struct PathMatchCandidateSet {
6192 pub snapshot: Snapshot,
6193 pub include_ignored: bool,
6194 pub include_root_name: bool,
6195 pub candidates: Candidates,
6196}
6197
6198pub enum Candidates {
6199 /// Only consider directories.
6200 Directories,
6201 /// Only consider files.
6202 Files,
6203 /// Consider directories and files.
6204 Entries,
6205}
6206
6207impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6208 type Candidates = PathMatchCandidateSetIter<'a>;
6209
6210 fn id(&self) -> usize {
6211 self.snapshot.id().to_usize()
6212 }
6213
6214 fn len(&self) -> usize {
6215 match self.candidates {
6216 Candidates::Files => {
6217 if self.include_ignored {
6218 self.snapshot.file_count()
6219 } else {
6220 self.snapshot.visible_file_count()
6221 }
6222 }
6223
6224 Candidates::Directories => {
6225 if self.include_ignored {
6226 self.snapshot.dir_count()
6227 } else {
6228 self.snapshot.visible_dir_count()
6229 }
6230 }
6231
6232 Candidates::Entries => {
6233 if self.include_ignored {
6234 self.snapshot.entry_count()
6235 } else {
6236 self.snapshot.visible_entry_count()
6237 }
6238 }
6239 }
6240 }
6241
6242 fn prefix(&self) -> Arc<RelPath> {
6243 if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
6244 self.snapshot.root_name().into()
6245 } else {
6246 RelPath::empty().into()
6247 }
6248 }
6249
6250 fn root_is_file(&self) -> bool {
6251 self.snapshot.root_entry().is_some_and(|f| f.is_file())
6252 }
6253
6254 fn path_style(&self) -> PathStyle {
6255 self.snapshot.path_style()
6256 }
6257
6258 fn candidates(&'a self, start: usize) -> Self::Candidates {
6259 PathMatchCandidateSetIter {
6260 traversal: match self.candidates {
6261 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
6262 Candidates::Files => self.snapshot.files(self.include_ignored, start),
6263 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
6264 },
6265 }
6266 }
6267}
6268
6269pub struct PathMatchCandidateSetIter<'a> {
6270 traversal: Traversal<'a>,
6271}
6272
6273impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6274 type Item = fuzzy::PathMatchCandidate<'a>;
6275
6276 fn next(&mut self) -> Option<Self::Item> {
6277 self.traversal
6278 .next()
6279 .map(|entry| fuzzy::PathMatchCandidate {
6280 is_dir: entry.kind.is_dir(),
6281 path: &entry.path,
6282 char_bag: entry.char_bag,
6283 })
6284 }
6285}
6286
6287impl<'a> fuzzy_nucleo::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6288 type Candidates = PathMatchCandidateSetNucleoIter<'a>;
6289 fn id(&self) -> usize {
6290 self.snapshot.id().to_usize()
6291 }
6292 fn len(&self) -> usize {
6293 match self.candidates {
6294 Candidates::Files => {
6295 if self.include_ignored {
6296 self.snapshot.file_count()
6297 } else {
6298 self.snapshot.visible_file_count()
6299 }
6300 }
6301 Candidates::Directories => {
6302 if self.include_ignored {
6303 self.snapshot.dir_count()
6304 } else {
6305 self.snapshot.visible_dir_count()
6306 }
6307 }
6308 Candidates::Entries => {
6309 if self.include_ignored {
6310 self.snapshot.entry_count()
6311 } else {
6312 self.snapshot.visible_entry_count()
6313 }
6314 }
6315 }
6316 }
6317 fn prefix(&self) -> Arc<RelPath> {
6318 if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
6319 self.snapshot.root_name().into()
6320 } else {
6321 RelPath::empty().into()
6322 }
6323 }
6324 fn root_is_file(&self) -> bool {
6325 self.snapshot.root_entry().is_some_and(|f| f.is_file())
6326 }
6327 fn path_style(&self) -> PathStyle {
6328 self.snapshot.path_style()
6329 }
6330 fn candidates(&'a self, start: usize) -> Self::Candidates {
6331 PathMatchCandidateSetNucleoIter {
6332 traversal: match self.candidates {
6333 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
6334 Candidates::Files => self.snapshot.files(self.include_ignored, start),
6335 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
6336 },
6337 }
6338 }
6339}
6340
6341pub struct PathMatchCandidateSetNucleoIter<'a> {
6342 traversal: Traversal<'a>,
6343}
6344
6345impl<'a> Iterator for PathMatchCandidateSetNucleoIter<'a> {
6346 type Item = fuzzy_nucleo::PathMatchCandidate<'a>;
6347 fn next(&mut self) -> Option<Self::Item> {
6348 self.traversal
6349 .next()
6350 .map(|entry| fuzzy_nucleo::PathMatchCandidate {
6351 is_dir: entry.kind.is_dir(),
6352 path: &entry.path,
6353 })
6354 }
6355}
6356
6357impl EventEmitter<Event> for Project {}
6358
6359impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
6360 fn from(val: &'a ProjectPath) -> Self {
6361 SettingsLocation {
6362 worktree_id: val.worktree_id,
6363 path: val.path.as_ref(),
6364 }
6365 }
6366}
6367
6368impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
6369 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6370 Self {
6371 worktree_id,
6372 path: path.into(),
6373 }
6374 }
6375}
6376
6377/// ResolvedPath is a path that has been resolved to either a ProjectPath
6378/// or an AbsPath and that *exists*.
6379#[derive(Debug, Clone)]
6380pub enum ResolvedPath {
6381 ProjectPath {
6382 project_path: ProjectPath,
6383 is_dir: bool,
6384 },
6385 AbsPath {
6386 path: String,
6387 is_dir: bool,
6388 },
6389}
6390
6391impl ResolvedPath {
6392 pub fn abs_path(&self) -> Option<&str> {
6393 match self {
6394 Self::AbsPath { path, .. } => Some(path),
6395 _ => None,
6396 }
6397 }
6398
6399 pub fn into_abs_path(self) -> Option<String> {
6400 match self {
6401 Self::AbsPath { path, .. } => Some(path),
6402 _ => None,
6403 }
6404 }
6405
6406 pub fn project_path(&self) -> Option<&ProjectPath> {
6407 match self {
6408 Self::ProjectPath { project_path, .. } => Some(project_path),
6409 _ => None,
6410 }
6411 }
6412
6413 pub fn is_file(&self) -> bool {
6414 !self.is_dir()
6415 }
6416
6417 pub fn is_dir(&self) -> bool {
6418 match self {
6419 Self::ProjectPath { is_dir, .. } => *is_dir,
6420 Self::AbsPath { is_dir, .. } => *is_dir,
6421 }
6422 }
6423}
6424
6425impl ProjectItem for Buffer {
6426 fn try_open(
6427 project: &Entity<Project>,
6428 path: &ProjectPath,
6429 cx: &mut App,
6430 ) -> Option<Task<Result<Entity<Self>>>> {
6431 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
6432 }
6433
6434 fn entry_id(&self, _cx: &App) -> Option<ProjectEntryId> {
6435 File::from_dyn(self.file()).and_then(|file| file.project_entry_id())
6436 }
6437
6438 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
6439 let file = self.file()?;
6440
6441 (!matches!(file.disk_state(), DiskState::Historic { .. })).then(|| ProjectPath {
6442 worktree_id: file.worktree_id(cx),
6443 path: file.path().clone(),
6444 })
6445 }
6446
6447 fn is_dirty(&self) -> bool {
6448 self.is_dirty()
6449 }
6450}
6451
6452impl Completion {
6453 pub fn kind(&self) -> Option<CompletionItemKind> {
6454 self.source
6455 // `lsp::CompletionListItemDefaults` has no `kind` field
6456 .lsp_completion(false)
6457 .and_then(|lsp_completion| lsp_completion.kind)
6458 }
6459
6460 pub fn label(&self) -> Option<String> {
6461 self.source
6462 .lsp_completion(false)
6463 .map(|lsp_completion| lsp_completion.label.clone())
6464 }
6465
6466 /// A key that can be used to sort completions when displaying
6467 /// them to the user.
6468 pub fn sort_key(&self) -> (usize, &str) {
6469 const DEFAULT_KIND_KEY: usize = 4;
6470 let kind_key = self
6471 .kind()
6472 .and_then(|lsp_completion_kind| match lsp_completion_kind {
6473 lsp::CompletionItemKind::KEYWORD => Some(0),
6474 lsp::CompletionItemKind::VARIABLE => Some(1),
6475 lsp::CompletionItemKind::CONSTANT => Some(2),
6476 lsp::CompletionItemKind::PROPERTY => Some(3),
6477 _ => None,
6478 })
6479 .unwrap_or(DEFAULT_KIND_KEY);
6480 (kind_key, self.label.filter_text())
6481 }
6482
6483 /// Whether this completion is a snippet.
6484 pub fn is_snippet_kind(&self) -> bool {
6485 matches!(
6486 &self.source,
6487 CompletionSource::Lsp { lsp_completion, .. }
6488 if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
6489 )
6490 }
6491
6492 /// Whether this completion is a snippet or snippet-style LSP completion.
6493 pub fn is_snippet(&self) -> bool {
6494 self.source
6495 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
6496 .lsp_completion(true)
6497 .is_some_and(|lsp_completion| {
6498 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
6499 })
6500 }
6501
6502 /// Returns the corresponding color for this completion.
6503 ///
6504 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
6505 pub fn color(&self) -> Option<Hsla> {
6506 // `lsp::CompletionListItemDefaults` has no `kind` field
6507 let lsp_completion = self.source.lsp_completion(false)?;
6508 if lsp_completion.kind? == CompletionItemKind::COLOR {
6509 return color_extractor::extract_color(&lsp_completion);
6510 }
6511 None
6512 }
6513}
6514
6515fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
6516 match level {
6517 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
6518 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
6519 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
6520 }
6521}
6522
6523fn provide_inline_values(
6524 captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
6525 snapshot: &language::BufferSnapshot,
6526 max_row: usize,
6527) -> Vec<InlineValueLocation> {
6528 let mut variables = Vec::new();
6529 let mut variable_position = HashSet::default();
6530 let mut scopes = Vec::new();
6531
6532 let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
6533
6534 for (capture_range, capture_kind) in captures {
6535 match capture_kind {
6536 language::DebuggerTextObject::Variable => {
6537 let variable_name = snapshot
6538 .text_for_range(capture_range.clone())
6539 .collect::<String>();
6540 let point = snapshot.offset_to_point(capture_range.end);
6541
6542 while scopes
6543 .last()
6544 .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
6545 {
6546 scopes.pop();
6547 }
6548
6549 if point.row as usize > max_row {
6550 break;
6551 }
6552
6553 let scope = if scopes
6554 .last()
6555 .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
6556 {
6557 VariableScope::Global
6558 } else {
6559 VariableScope::Local
6560 };
6561
6562 if variable_position.insert(capture_range.end) {
6563 variables.push(InlineValueLocation {
6564 variable_name,
6565 scope,
6566 lookup: VariableLookupKind::Variable,
6567 row: point.row as usize,
6568 column: point.column as usize,
6569 });
6570 }
6571 }
6572 language::DebuggerTextObject::Scope => {
6573 while scopes.last().map_or_else(
6574 || false,
6575 |scope: &Range<usize>| {
6576 !(scope.contains(&capture_range.start)
6577 && scope.contains(&capture_range.end))
6578 },
6579 ) {
6580 scopes.pop();
6581 }
6582 scopes.push(capture_range);
6583 }
6584 }
6585 }
6586
6587 variables
6588}