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