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