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