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