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