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