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