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