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