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