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