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