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