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