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, PartialEq)]
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 pub fn definitions<T: ToPointUtf16>(
3346 &mut self,
3347 buffer: &Entity<Buffer>,
3348 position: T,
3349 cx: &mut Context<Self>,
3350 ) -> Task<Result<Vec<LocationLink>>> {
3351 let position = position.to_point_utf16(buffer.read(cx));
3352 self.lsp_store.update(cx, |lsp_store, cx| {
3353 lsp_store.definitions(buffer, position, cx)
3354 })
3355 }
3356
3357 pub fn declarations<T: ToPointUtf16>(
3358 &mut self,
3359 buffer: &Entity<Buffer>,
3360 position: T,
3361 cx: &mut Context<Self>,
3362 ) -> Task<Result<Vec<LocationLink>>> {
3363 let position = position.to_point_utf16(buffer.read(cx));
3364 self.lsp_store.update(cx, |lsp_store, cx| {
3365 lsp_store.declarations(buffer, position, cx)
3366 })
3367 }
3368
3369 pub fn type_definitions<T: ToPointUtf16>(
3370 &mut self,
3371 buffer: &Entity<Buffer>,
3372 position: T,
3373 cx: &mut Context<Self>,
3374 ) -> Task<Result<Vec<LocationLink>>> {
3375 let position = position.to_point_utf16(buffer.read(cx));
3376 self.lsp_store.update(cx, |lsp_store, cx| {
3377 lsp_store.type_definitions(buffer, position, cx)
3378 })
3379 }
3380
3381 pub fn implementations<T: ToPointUtf16>(
3382 &mut self,
3383 buffer: &Entity<Buffer>,
3384 position: T,
3385 cx: &mut Context<Self>,
3386 ) -> Task<Result<Vec<LocationLink>>> {
3387 let position = position.to_point_utf16(buffer.read(cx));
3388 self.lsp_store.update(cx, |lsp_store, cx| {
3389 lsp_store.implementations(buffer, position, cx)
3390 })
3391 }
3392
3393 pub fn references<T: ToPointUtf16>(
3394 &mut self,
3395 buffer: &Entity<Buffer>,
3396 position: T,
3397 cx: &mut Context<Self>,
3398 ) -> Task<Result<Vec<Location>>> {
3399 let position = position.to_point_utf16(buffer.read(cx));
3400 self.lsp_store.update(cx, |lsp_store, cx| {
3401 lsp_store.references(buffer, position, cx)
3402 })
3403 }
3404
3405 fn document_highlights_impl(
3406 &mut self,
3407 buffer: &Entity<Buffer>,
3408 position: PointUtf16,
3409 cx: &mut Context<Self>,
3410 ) -> Task<Result<Vec<DocumentHighlight>>> {
3411 self.request_lsp(
3412 buffer.clone(),
3413 LanguageServerToQuery::FirstCapable,
3414 GetDocumentHighlights { position },
3415 cx,
3416 )
3417 }
3418
3419 pub fn document_highlights<T: ToPointUtf16>(
3420 &mut self,
3421 buffer: &Entity<Buffer>,
3422 position: T,
3423 cx: &mut Context<Self>,
3424 ) -> Task<Result<Vec<DocumentHighlight>>> {
3425 let position = position.to_point_utf16(buffer.read(cx));
3426 self.document_highlights_impl(buffer, position, cx)
3427 }
3428
3429 pub fn document_symbols(
3430 &mut self,
3431 buffer: &Entity<Buffer>,
3432 cx: &mut Context<Self>,
3433 ) -> Task<Result<Vec<DocumentSymbol>>> {
3434 self.request_lsp(
3435 buffer.clone(),
3436 LanguageServerToQuery::FirstCapable,
3437 GetDocumentSymbols,
3438 cx,
3439 )
3440 }
3441
3442 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3443 self.lsp_store
3444 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3445 }
3446
3447 pub fn open_buffer_for_symbol(
3448 &mut self,
3449 symbol: &Symbol,
3450 cx: &mut Context<Self>,
3451 ) -> Task<Result<Entity<Buffer>>> {
3452 self.lsp_store.update(cx, |lsp_store, cx| {
3453 lsp_store.open_buffer_for_symbol(symbol, cx)
3454 })
3455 }
3456
3457 pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3458 let guard = self.retain_remotely_created_models(cx);
3459 let Some(ssh_client) = self.ssh_client.as_ref() else {
3460 return Task::ready(Err(anyhow!("not an ssh project")));
3461 };
3462
3463 let proto_client = ssh_client.read(cx).proto_client();
3464
3465 cx.spawn(async move |project, cx| {
3466 let buffer = proto_client
3467 .request(proto::OpenServerSettings {
3468 project_id: SSH_PROJECT_ID,
3469 })
3470 .await?;
3471
3472 let buffer = project
3473 .update(cx, |project, cx| {
3474 project.buffer_store.update(cx, |buffer_store, cx| {
3475 anyhow::Ok(
3476 buffer_store
3477 .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3478 )
3479 })
3480 })??
3481 .await;
3482
3483 drop(guard);
3484 buffer
3485 })
3486 }
3487
3488 pub fn open_local_buffer_via_lsp(
3489 &mut self,
3490 abs_path: lsp::Url,
3491 language_server_id: LanguageServerId,
3492 language_server_name: LanguageServerName,
3493 cx: &mut Context<Self>,
3494 ) -> Task<Result<Entity<Buffer>>> {
3495 self.lsp_store.update(cx, |lsp_store, cx| {
3496 lsp_store.open_local_buffer_via_lsp(
3497 abs_path,
3498 language_server_id,
3499 language_server_name,
3500 cx,
3501 )
3502 })
3503 }
3504
3505 pub fn signature_help<T: ToPointUtf16>(
3506 &self,
3507 buffer: &Entity<Buffer>,
3508 position: T,
3509 cx: &mut Context<Self>,
3510 ) -> Task<Vec<SignatureHelp>> {
3511 self.lsp_store.update(cx, |lsp_store, cx| {
3512 lsp_store.signature_help(buffer, position, cx)
3513 })
3514 }
3515
3516 pub fn hover<T: ToPointUtf16>(
3517 &self,
3518 buffer: &Entity<Buffer>,
3519 position: T,
3520 cx: &mut Context<Self>,
3521 ) -> Task<Vec<Hover>> {
3522 let position = position.to_point_utf16(buffer.read(cx));
3523 self.lsp_store
3524 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3525 }
3526
3527 pub fn linked_edit(
3528 &self,
3529 buffer: &Entity<Buffer>,
3530 position: Anchor,
3531 cx: &mut Context<Self>,
3532 ) -> Task<Result<Vec<Range<Anchor>>>> {
3533 self.lsp_store.update(cx, |lsp_store, cx| {
3534 lsp_store.linked_edit(buffer, position, cx)
3535 })
3536 }
3537
3538 pub fn completions<T: ToOffset + ToPointUtf16>(
3539 &self,
3540 buffer: &Entity<Buffer>,
3541 position: T,
3542 context: CompletionContext,
3543 cx: &mut Context<Self>,
3544 ) -> Task<Result<Vec<CompletionResponse>>> {
3545 let position = position.to_point_utf16(buffer.read(cx));
3546 self.lsp_store.update(cx, |lsp_store, cx| {
3547 lsp_store.completions(buffer, position, context, cx)
3548 })
3549 }
3550
3551 pub fn code_actions<T: Clone + ToOffset>(
3552 &mut self,
3553 buffer_handle: &Entity<Buffer>,
3554 range: Range<T>,
3555 kinds: Option<Vec<CodeActionKind>>,
3556 cx: &mut Context<Self>,
3557 ) -> Task<Result<Vec<CodeAction>>> {
3558 let buffer = buffer_handle.read(cx);
3559 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3560 self.lsp_store.update(cx, |lsp_store, cx| {
3561 lsp_store.code_actions(buffer_handle, range, kinds, cx)
3562 })
3563 }
3564
3565 pub fn code_lens<T: Clone + ToOffset>(
3566 &mut self,
3567 buffer_handle: &Entity<Buffer>,
3568 range: Range<T>,
3569 cx: &mut Context<Self>,
3570 ) -> Task<Result<Vec<CodeAction>>> {
3571 let snapshot = buffer_handle.read(cx).snapshot();
3572 let range = snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end);
3573 let code_lens_actions = self
3574 .lsp_store
3575 .update(cx, |lsp_store, cx| lsp_store.code_lens(buffer_handle, cx));
3576
3577 cx.background_spawn(async move {
3578 let mut code_lens_actions = code_lens_actions.await?;
3579 code_lens_actions.retain(|code_lens_action| {
3580 range
3581 .start
3582 .cmp(&code_lens_action.range.start, &snapshot)
3583 .is_ge()
3584 && range
3585 .end
3586 .cmp(&code_lens_action.range.end, &snapshot)
3587 .is_le()
3588 });
3589 Ok(code_lens_actions)
3590 })
3591 }
3592
3593 pub fn apply_code_action(
3594 &self,
3595 buffer_handle: Entity<Buffer>,
3596 action: CodeAction,
3597 push_to_history: bool,
3598 cx: &mut Context<Self>,
3599 ) -> Task<Result<ProjectTransaction>> {
3600 self.lsp_store.update(cx, |lsp_store, cx| {
3601 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3602 })
3603 }
3604
3605 pub fn apply_code_action_kind(
3606 &self,
3607 buffers: HashSet<Entity<Buffer>>,
3608 kind: CodeActionKind,
3609 push_to_history: bool,
3610 cx: &mut Context<Self>,
3611 ) -> Task<Result<ProjectTransaction>> {
3612 self.lsp_store.update(cx, |lsp_store, cx| {
3613 lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
3614 })
3615 }
3616
3617 fn prepare_rename_impl(
3618 &mut self,
3619 buffer: Entity<Buffer>,
3620 position: PointUtf16,
3621 cx: &mut Context<Self>,
3622 ) -> Task<Result<PrepareRenameResponse>> {
3623 self.request_lsp(
3624 buffer,
3625 LanguageServerToQuery::FirstCapable,
3626 PrepareRename { position },
3627 cx,
3628 )
3629 }
3630 pub fn prepare_rename<T: ToPointUtf16>(
3631 &mut self,
3632 buffer: Entity<Buffer>,
3633 position: T,
3634 cx: &mut Context<Self>,
3635 ) -> Task<Result<PrepareRenameResponse>> {
3636 let position = position.to_point_utf16(buffer.read(cx));
3637 self.prepare_rename_impl(buffer, position, cx)
3638 }
3639
3640 pub fn perform_rename<T: ToPointUtf16>(
3641 &mut self,
3642 buffer: Entity<Buffer>,
3643 position: T,
3644 new_name: String,
3645 cx: &mut Context<Self>,
3646 ) -> Task<Result<ProjectTransaction>> {
3647 let push_to_history = true;
3648 let position = position.to_point_utf16(buffer.read(cx));
3649 self.request_lsp(
3650 buffer,
3651 LanguageServerToQuery::FirstCapable,
3652 PerformRename {
3653 position,
3654 new_name,
3655 push_to_history,
3656 },
3657 cx,
3658 )
3659 }
3660
3661 pub fn on_type_format<T: ToPointUtf16>(
3662 &mut self,
3663 buffer: Entity<Buffer>,
3664 position: T,
3665 trigger: String,
3666 push_to_history: bool,
3667 cx: &mut Context<Self>,
3668 ) -> Task<Result<Option<Transaction>>> {
3669 self.lsp_store.update(cx, |lsp_store, cx| {
3670 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3671 })
3672 }
3673
3674 pub fn inline_values(
3675 &mut self,
3676 session: Entity<Session>,
3677 active_stack_frame: ActiveStackFrame,
3678 buffer_handle: Entity<Buffer>,
3679 range: Range<text::Anchor>,
3680 cx: &mut Context<Self>,
3681 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3682 let snapshot = buffer_handle.read(cx).snapshot();
3683
3684 let captures = snapshot.debug_variables_query(Anchor::MIN..range.end);
3685
3686 let row = snapshot
3687 .summary_for_anchor::<text::PointUtf16>(&range.end)
3688 .row as usize;
3689
3690 let inline_value_locations = provide_inline_values(captures, &snapshot, row);
3691
3692 let stack_frame_id = active_stack_frame.stack_frame_id;
3693 cx.spawn(async move |this, cx| {
3694 this.update(cx, |project, cx| {
3695 project.dap_store().update(cx, |dap_store, cx| {
3696 dap_store.resolve_inline_value_locations(
3697 session,
3698 stack_frame_id,
3699 buffer_handle,
3700 inline_value_locations,
3701 cx,
3702 )
3703 })
3704 })?
3705 .await
3706 })
3707 }
3708
3709 pub fn inlay_hints<T: ToOffset>(
3710 &mut self,
3711 buffer_handle: Entity<Buffer>,
3712 range: Range<T>,
3713 cx: &mut Context<Self>,
3714 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3715 let buffer = buffer_handle.read(cx);
3716 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3717 self.lsp_store.update(cx, |lsp_store, cx| {
3718 lsp_store.inlay_hints(buffer_handle, range, cx)
3719 })
3720 }
3721
3722 pub fn resolve_inlay_hint(
3723 &self,
3724 hint: InlayHint,
3725 buffer_handle: Entity<Buffer>,
3726 server_id: LanguageServerId,
3727 cx: &mut Context<Self>,
3728 ) -> Task<anyhow::Result<InlayHint>> {
3729 self.lsp_store.update(cx, |lsp_store, cx| {
3730 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3731 })
3732 }
3733
3734 pub fn update_diagnostics(
3735 &mut self,
3736 language_server_id: LanguageServerId,
3737 source_kind: DiagnosticSourceKind,
3738 result_id: Option<String>,
3739 params: lsp::PublishDiagnosticsParams,
3740 disk_based_sources: &[String],
3741 cx: &mut Context<Self>,
3742 ) -> Result<(), anyhow::Error> {
3743 self.lsp_store.update(cx, |lsp_store, cx| {
3744 lsp_store.update_diagnostics(
3745 language_server_id,
3746 params,
3747 result_id,
3748 source_kind,
3749 disk_based_sources,
3750 cx,
3751 )
3752 })
3753 }
3754
3755 pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3756 let (result_tx, result_rx) = smol::channel::unbounded();
3757
3758 let matching_buffers_rx = if query.is_opened_only() {
3759 self.sort_search_candidates(&query, cx)
3760 } else {
3761 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3762 };
3763
3764 cx.spawn(async move |_, cx| {
3765 let mut range_count = 0;
3766 let mut buffer_count = 0;
3767 let mut limit_reached = false;
3768 let query = Arc::new(query);
3769 let chunks = matching_buffers_rx.ready_chunks(64);
3770
3771 // Now that we know what paths match the query, we will load at most
3772 // 64 buffers at a time to avoid overwhelming the main thread. For each
3773 // opened buffer, we will spawn a background task that retrieves all the
3774 // ranges in the buffer matched by the query.
3775 let mut chunks = pin!(chunks);
3776 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3777 let mut chunk_results = Vec::with_capacity(matching_buffer_chunk.len());
3778 for buffer in matching_buffer_chunk {
3779 let query = query.clone();
3780 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
3781 chunk_results.push(cx.background_spawn(async move {
3782 let ranges = query
3783 .search(&snapshot, None)
3784 .await
3785 .iter()
3786 .map(|range| {
3787 snapshot.anchor_before(range.start)
3788 ..snapshot.anchor_after(range.end)
3789 })
3790 .collect::<Vec<_>>();
3791 anyhow::Ok((buffer, ranges))
3792 }));
3793 }
3794
3795 let chunk_results = futures::future::join_all(chunk_results).await;
3796 for result in chunk_results {
3797 if let Some((buffer, ranges)) = result.log_err() {
3798 range_count += ranges.len();
3799 buffer_count += 1;
3800 result_tx
3801 .send(SearchResult::Buffer { buffer, ranges })
3802 .await?;
3803 if buffer_count > MAX_SEARCH_RESULT_FILES
3804 || range_count > MAX_SEARCH_RESULT_RANGES
3805 {
3806 limit_reached = true;
3807 break 'outer;
3808 }
3809 }
3810 }
3811 }
3812
3813 if limit_reached {
3814 result_tx.send(SearchResult::LimitReached).await?;
3815 }
3816
3817 anyhow::Ok(())
3818 })
3819 .detach();
3820
3821 result_rx
3822 }
3823
3824 fn find_search_candidate_buffers(
3825 &mut self,
3826 query: &SearchQuery,
3827 limit: usize,
3828 cx: &mut Context<Project>,
3829 ) -> Receiver<Entity<Buffer>> {
3830 if self.is_local() {
3831 let fs = self.fs.clone();
3832 self.buffer_store.update(cx, |buffer_store, cx| {
3833 buffer_store.find_search_candidates(query, limit, fs, cx)
3834 })
3835 } else {
3836 self.find_search_candidates_remote(query, limit, cx)
3837 }
3838 }
3839
3840 fn sort_search_candidates(
3841 &mut self,
3842 search_query: &SearchQuery,
3843 cx: &mut Context<Project>,
3844 ) -> Receiver<Entity<Buffer>> {
3845 let worktree_store = self.worktree_store.read(cx);
3846 let mut buffers = search_query
3847 .buffers()
3848 .into_iter()
3849 .flatten()
3850 .filter(|buffer| {
3851 let b = buffer.read(cx);
3852 if let Some(file) = b.file() {
3853 if !search_query.match_path(file.path()) {
3854 return false;
3855 }
3856 if let Some(entry) = b
3857 .entry_id(cx)
3858 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3859 {
3860 if entry.is_ignored && !search_query.include_ignored() {
3861 return false;
3862 }
3863 }
3864 }
3865 true
3866 })
3867 .collect::<Vec<_>>();
3868 let (tx, rx) = smol::channel::unbounded();
3869 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3870 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3871 (None, Some(_)) => std::cmp::Ordering::Less,
3872 (Some(_), None) => std::cmp::Ordering::Greater,
3873 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3874 });
3875 for buffer in buffers {
3876 tx.send_blocking(buffer.clone()).unwrap()
3877 }
3878
3879 rx
3880 }
3881
3882 fn find_search_candidates_remote(
3883 &mut self,
3884 query: &SearchQuery,
3885 limit: usize,
3886 cx: &mut Context<Project>,
3887 ) -> Receiver<Entity<Buffer>> {
3888 let (tx, rx) = smol::channel::unbounded();
3889
3890 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3891 (ssh_client.read(cx).proto_client(), 0)
3892 } else if let Some(remote_id) = self.remote_id() {
3893 (self.client.clone().into(), remote_id)
3894 } else {
3895 return rx;
3896 };
3897
3898 let request = client.request(proto::FindSearchCandidates {
3899 project_id: remote_id,
3900 query: Some(query.to_proto()),
3901 limit: limit as _,
3902 });
3903 let guard = self.retain_remotely_created_models(cx);
3904
3905 cx.spawn(async move |project, cx| {
3906 let response = request.await?;
3907 for buffer_id in response.buffer_ids {
3908 let buffer_id = BufferId::new(buffer_id)?;
3909 let buffer = project
3910 .update(cx, |project, cx| {
3911 project.buffer_store.update(cx, |buffer_store, cx| {
3912 buffer_store.wait_for_remote_buffer(buffer_id, cx)
3913 })
3914 })?
3915 .await?;
3916 let _ = tx.send(buffer).await;
3917 }
3918
3919 drop(guard);
3920 anyhow::Ok(())
3921 })
3922 .detach_and_log_err(cx);
3923 rx
3924 }
3925
3926 pub fn request_lsp<R: LspCommand>(
3927 &mut self,
3928 buffer_handle: Entity<Buffer>,
3929 server: LanguageServerToQuery,
3930 request: R,
3931 cx: &mut Context<Self>,
3932 ) -> Task<Result<R::Response>>
3933 where
3934 <R::LspRequest as lsp::request::Request>::Result: Send,
3935 <R::LspRequest as lsp::request::Request>::Params: Send,
3936 {
3937 let guard = self.retain_remotely_created_models(cx);
3938 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3939 lsp_store.request_lsp(buffer_handle, server, request, cx)
3940 });
3941 cx.spawn(async move |_, _| {
3942 let result = task.await;
3943 drop(guard);
3944 result
3945 })
3946 }
3947
3948 /// Move a worktree to a new position in the worktree order.
3949 ///
3950 /// The worktree will moved to the opposite side of the destination worktree.
3951 ///
3952 /// # Example
3953 ///
3954 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3955 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3956 ///
3957 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3958 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3959 ///
3960 /// # Errors
3961 ///
3962 /// An error will be returned if the worktree or destination worktree are not found.
3963 pub fn move_worktree(
3964 &mut self,
3965 source: WorktreeId,
3966 destination: WorktreeId,
3967 cx: &mut Context<Self>,
3968 ) -> Result<()> {
3969 self.worktree_store.update(cx, |worktree_store, cx| {
3970 worktree_store.move_worktree(source, destination, cx)
3971 })
3972 }
3973
3974 pub fn find_or_create_worktree(
3975 &mut self,
3976 abs_path: impl AsRef<Path>,
3977 visible: bool,
3978 cx: &mut Context<Self>,
3979 ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3980 self.worktree_store.update(cx, |worktree_store, cx| {
3981 worktree_store.find_or_create_worktree(abs_path, visible, cx)
3982 })
3983 }
3984
3985 pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3986 self.worktree_store.read(cx).find_worktree(abs_path, cx)
3987 }
3988
3989 pub fn is_shared(&self) -> bool {
3990 match &self.client_state {
3991 ProjectClientState::Shared { .. } => true,
3992 ProjectClientState::Local => false,
3993 ProjectClientState::Remote { .. } => true,
3994 }
3995 }
3996
3997 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3998 pub fn resolve_path_in_buffer(
3999 &self,
4000 path: &str,
4001 buffer: &Entity<Buffer>,
4002 cx: &mut Context<Self>,
4003 ) -> Task<Option<ResolvedPath>> {
4004 let path_buf = PathBuf::from(path);
4005 if path_buf.is_absolute() || path.starts_with("~") {
4006 self.resolve_abs_path(path, cx)
4007 } else {
4008 self.resolve_path_in_worktrees(path_buf, buffer, cx)
4009 }
4010 }
4011
4012 pub fn resolve_abs_file_path(
4013 &self,
4014 path: &str,
4015 cx: &mut Context<Self>,
4016 ) -> Task<Option<ResolvedPath>> {
4017 let resolve_task = self.resolve_abs_path(path, cx);
4018 cx.background_spawn(async move {
4019 let resolved_path = resolve_task.await;
4020 resolved_path.filter(|path| path.is_file())
4021 })
4022 }
4023
4024 pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4025 if self.is_local() {
4026 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4027 let fs = self.fs.clone();
4028 cx.background_spawn(async move {
4029 let path = expanded.as_path();
4030 let metadata = fs.metadata(path).await.ok().flatten();
4031
4032 metadata.map(|metadata| ResolvedPath::AbsPath {
4033 path: expanded,
4034 is_dir: metadata.is_dir,
4035 })
4036 })
4037 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
4038 let request_path = Path::new(path);
4039 let request = ssh_client
4040 .read(cx)
4041 .proto_client()
4042 .request(proto::GetPathMetadata {
4043 project_id: SSH_PROJECT_ID,
4044 path: request_path.to_proto(),
4045 });
4046 cx.background_spawn(async move {
4047 let response = request.await.log_err()?;
4048 if response.exists {
4049 Some(ResolvedPath::AbsPath {
4050 path: PathBuf::from_proto(response.path),
4051 is_dir: response.is_dir,
4052 })
4053 } else {
4054 None
4055 }
4056 })
4057 } else {
4058 return Task::ready(None);
4059 }
4060 }
4061
4062 fn resolve_path_in_worktrees(
4063 &self,
4064 path: PathBuf,
4065 buffer: &Entity<Buffer>,
4066 cx: &mut Context<Self>,
4067 ) -> Task<Option<ResolvedPath>> {
4068 let mut candidates = vec![path.clone()];
4069
4070 if let Some(file) = buffer.read(cx).file() {
4071 if let Some(dir) = file.path().parent() {
4072 let joined = dir.to_path_buf().join(path);
4073 candidates.push(joined);
4074 }
4075 }
4076
4077 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4078 let worktrees_with_ids: Vec<_> = self
4079 .worktrees(cx)
4080 .map(|worktree| {
4081 let id = worktree.read(cx).id();
4082 (worktree, id)
4083 })
4084 .collect();
4085
4086 cx.spawn(async move |_, mut cx| {
4087 if let Some(buffer_worktree_id) = buffer_worktree_id {
4088 if let Some((worktree, _)) = worktrees_with_ids
4089 .iter()
4090 .find(|(_, id)| *id == buffer_worktree_id)
4091 {
4092 for candidate in candidates.iter() {
4093 if let Some(path) =
4094 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
4095 {
4096 return Some(path);
4097 }
4098 }
4099 }
4100 }
4101 for (worktree, id) in worktrees_with_ids {
4102 if Some(id) == buffer_worktree_id {
4103 continue;
4104 }
4105 for candidate in candidates.iter() {
4106 if let Some(path) =
4107 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
4108 {
4109 return Some(path);
4110 }
4111 }
4112 }
4113 None
4114 })
4115 }
4116
4117 fn resolve_path_in_worktree(
4118 worktree: &Entity<Worktree>,
4119 path: &PathBuf,
4120 cx: &mut AsyncApp,
4121 ) -> Option<ResolvedPath> {
4122 worktree
4123 .read_with(cx, |worktree, _| {
4124 let root_entry_path = &worktree.root_entry()?.path;
4125 let resolved = resolve_path(root_entry_path, path);
4126 let stripped = resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
4127 worktree.entry_for_path(stripped).map(|entry| {
4128 let project_path = ProjectPath {
4129 worktree_id: worktree.id(),
4130 path: entry.path.clone(),
4131 };
4132 ResolvedPath::ProjectPath {
4133 project_path,
4134 is_dir: entry.is_dir(),
4135 }
4136 })
4137 })
4138 .ok()?
4139 }
4140
4141 pub fn list_directory(
4142 &self,
4143 query: String,
4144 cx: &mut Context<Self>,
4145 ) -> Task<Result<Vec<DirectoryItem>>> {
4146 if self.is_local() {
4147 DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4148 } else if let Some(session) = self.ssh_client.as_ref() {
4149 let path_buf = PathBuf::from(query);
4150 let request = proto::ListRemoteDirectory {
4151 dev_server_id: SSH_PROJECT_ID,
4152 path: path_buf.to_proto(),
4153 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4154 };
4155
4156 let response = session.read(cx).proto_client().request(request);
4157 cx.background_spawn(async move {
4158 let proto::ListRemoteDirectoryResponse {
4159 entries,
4160 entry_info,
4161 } = response.await?;
4162 Ok(entries
4163 .into_iter()
4164 .zip(entry_info)
4165 .map(|(entry, info)| DirectoryItem {
4166 path: PathBuf::from(entry),
4167 is_dir: info.is_dir,
4168 })
4169 .collect())
4170 })
4171 } else {
4172 Task::ready(Err(anyhow!("cannot list directory in remote project")))
4173 }
4174 }
4175
4176 pub fn create_worktree(
4177 &mut self,
4178 abs_path: impl AsRef<Path>,
4179 visible: bool,
4180 cx: &mut Context<Self>,
4181 ) -> Task<Result<Entity<Worktree>>> {
4182 self.worktree_store.update(cx, |worktree_store, cx| {
4183 worktree_store.create_worktree(abs_path, visible, cx)
4184 })
4185 }
4186
4187 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4188 self.worktree_store.update(cx, |worktree_store, cx| {
4189 worktree_store.remove_worktree(id_to_remove, cx);
4190 });
4191 }
4192
4193 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4194 self.worktree_store.update(cx, |worktree_store, cx| {
4195 worktree_store.add(worktree, cx);
4196 });
4197 }
4198
4199 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4200 let new_active_entry = entry.and_then(|project_path| {
4201 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4202 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4203 Some(entry.id)
4204 });
4205 if new_active_entry != self.active_entry {
4206 self.active_entry = new_active_entry;
4207 self.lsp_store.update(cx, |lsp_store, _| {
4208 lsp_store.set_active_entry(new_active_entry);
4209 });
4210 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4211 }
4212 }
4213
4214 pub fn language_servers_running_disk_based_diagnostics<'a>(
4215 &'a self,
4216 cx: &'a App,
4217 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4218 self.lsp_store
4219 .read(cx)
4220 .language_servers_running_disk_based_diagnostics()
4221 }
4222
4223 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4224 self.lsp_store
4225 .read(cx)
4226 .diagnostic_summary(include_ignored, cx)
4227 }
4228
4229 pub fn diagnostic_summaries<'a>(
4230 &'a self,
4231 include_ignored: bool,
4232 cx: &'a App,
4233 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4234 self.lsp_store
4235 .read(cx)
4236 .diagnostic_summaries(include_ignored, cx)
4237 }
4238
4239 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4240 self.active_entry
4241 }
4242
4243 pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
4244 self.worktree_store.read(cx).entry_for_path(path, cx)
4245 }
4246
4247 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4248 let worktree = self.worktree_for_entry(entry_id, cx)?;
4249 let worktree = worktree.read(cx);
4250 let worktree_id = worktree.id();
4251 let path = worktree.entry_for_id(entry_id)?.path.clone();
4252 Some(ProjectPath { worktree_id, path })
4253 }
4254
4255 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4256 self.worktree_for_id(project_path.worktree_id, cx)?
4257 .read(cx)
4258 .absolutize(&project_path.path)
4259 .ok()
4260 }
4261
4262 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4263 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4264 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4265 /// the first visible worktree that has an entry for that relative path.
4266 ///
4267 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4268 /// root name from paths.
4269 ///
4270 /// # Arguments
4271 ///
4272 /// * `path` - A full path that starts with a worktree root name, or alternatively a
4273 /// relative path within a visible worktree.
4274 /// * `cx` - A reference to the `AppContext`.
4275 ///
4276 /// # Returns
4277 ///
4278 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4279 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4280 let path = path.as_ref();
4281 let worktree_store = self.worktree_store.read(cx);
4282
4283 if path.is_absolute() {
4284 for worktree in worktree_store.visible_worktrees(cx) {
4285 let worktree_abs_path = worktree.read(cx).abs_path();
4286
4287 if let Ok(relative_path) = path.strip_prefix(worktree_abs_path) {
4288 return Some(ProjectPath {
4289 worktree_id: worktree.read(cx).id(),
4290 path: relative_path.into(),
4291 });
4292 }
4293 }
4294 } else {
4295 for worktree in worktree_store.visible_worktrees(cx) {
4296 let worktree_root_name = worktree.read(cx).root_name();
4297 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
4298 return Some(ProjectPath {
4299 worktree_id: worktree.read(cx).id(),
4300 path: relative_path.into(),
4301 });
4302 }
4303 }
4304
4305 for worktree in worktree_store.visible_worktrees(cx) {
4306 let worktree = worktree.read(cx);
4307 if let Some(entry) = worktree.entry_for_path(path) {
4308 return Some(ProjectPath {
4309 worktree_id: worktree.id(),
4310 path: entry.path.clone(),
4311 });
4312 }
4313 }
4314 }
4315
4316 None
4317 }
4318
4319 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4320 self.find_worktree(abs_path, cx)
4321 .map(|(worktree, relative_path)| ProjectPath {
4322 worktree_id: worktree.read(cx).id(),
4323 path: relative_path.into(),
4324 })
4325 }
4326
4327 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4328 Some(
4329 self.worktree_for_id(project_path.worktree_id, cx)?
4330 .read(cx)
4331 .abs_path()
4332 .to_path_buf(),
4333 )
4334 }
4335
4336 pub fn blame_buffer(
4337 &self,
4338 buffer: &Entity<Buffer>,
4339 version: Option<clock::Global>,
4340 cx: &mut App,
4341 ) -> Task<Result<Option<Blame>>> {
4342 self.git_store.update(cx, |git_store, cx| {
4343 git_store.blame_buffer(buffer, version, cx)
4344 })
4345 }
4346
4347 pub fn get_permalink_to_line(
4348 &self,
4349 buffer: &Entity<Buffer>,
4350 selection: Range<u32>,
4351 cx: &mut App,
4352 ) -> Task<Result<url::Url>> {
4353 self.git_store.update(cx, |git_store, cx| {
4354 git_store.get_permalink_to_line(buffer, selection, cx)
4355 })
4356 }
4357
4358 // RPC message handlers
4359
4360 async fn handle_unshare_project(
4361 this: Entity<Self>,
4362 _: TypedEnvelope<proto::UnshareProject>,
4363 mut cx: AsyncApp,
4364 ) -> Result<()> {
4365 this.update(&mut cx, |this, cx| {
4366 if this.is_local() || this.is_via_ssh() {
4367 this.unshare(cx)?;
4368 } else {
4369 this.disconnected_from_host(cx);
4370 }
4371 Ok(())
4372 })?
4373 }
4374
4375 async fn handle_add_collaborator(
4376 this: Entity<Self>,
4377 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4378 mut cx: AsyncApp,
4379 ) -> Result<()> {
4380 let collaborator = envelope
4381 .payload
4382 .collaborator
4383 .take()
4384 .context("empty collaborator")?;
4385
4386 let collaborator = Collaborator::from_proto(collaborator)?;
4387 this.update(&mut cx, |this, cx| {
4388 this.buffer_store.update(cx, |buffer_store, _| {
4389 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4390 });
4391 this.breakpoint_store.read(cx).broadcast();
4392 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4393 this.collaborators
4394 .insert(collaborator.peer_id, collaborator);
4395 })?;
4396
4397 Ok(())
4398 }
4399
4400 async fn handle_update_project_collaborator(
4401 this: Entity<Self>,
4402 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4403 mut cx: AsyncApp,
4404 ) -> Result<()> {
4405 let old_peer_id = envelope
4406 .payload
4407 .old_peer_id
4408 .context("missing old peer id")?;
4409 let new_peer_id = envelope
4410 .payload
4411 .new_peer_id
4412 .context("missing new peer id")?;
4413 this.update(&mut cx, |this, cx| {
4414 let collaborator = this
4415 .collaborators
4416 .remove(&old_peer_id)
4417 .context("received UpdateProjectCollaborator for unknown peer")?;
4418 let is_host = collaborator.is_host;
4419 this.collaborators.insert(new_peer_id, collaborator);
4420
4421 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4422 this.buffer_store.update(cx, |buffer_store, _| {
4423 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4424 });
4425
4426 if is_host {
4427 this.buffer_store
4428 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4429 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4430 .unwrap();
4431 cx.emit(Event::HostReshared);
4432 }
4433
4434 cx.emit(Event::CollaboratorUpdated {
4435 old_peer_id,
4436 new_peer_id,
4437 });
4438 Ok(())
4439 })?
4440 }
4441
4442 async fn handle_remove_collaborator(
4443 this: Entity<Self>,
4444 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4445 mut cx: AsyncApp,
4446 ) -> Result<()> {
4447 this.update(&mut cx, |this, cx| {
4448 let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4449 let replica_id = this
4450 .collaborators
4451 .remove(&peer_id)
4452 .with_context(|| format!("unknown peer {peer_id:?}"))?
4453 .replica_id;
4454 this.buffer_store.update(cx, |buffer_store, cx| {
4455 buffer_store.forget_shared_buffers_for(&peer_id);
4456 for buffer in buffer_store.buffers() {
4457 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4458 }
4459 });
4460 this.git_store.update(cx, |git_store, _| {
4461 git_store.forget_shared_diffs_for(&peer_id);
4462 });
4463
4464 cx.emit(Event::CollaboratorLeft(peer_id));
4465 Ok(())
4466 })?
4467 }
4468
4469 async fn handle_update_project(
4470 this: Entity<Self>,
4471 envelope: TypedEnvelope<proto::UpdateProject>,
4472 mut cx: AsyncApp,
4473 ) -> Result<()> {
4474 this.update(&mut cx, |this, cx| {
4475 // Don't handle messages that were sent before the response to us joining the project
4476 if envelope.message_id > this.join_project_response_message_id {
4477 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4478 }
4479 Ok(())
4480 })?
4481 }
4482
4483 async fn handle_toast(
4484 this: Entity<Self>,
4485 envelope: TypedEnvelope<proto::Toast>,
4486 mut cx: AsyncApp,
4487 ) -> Result<()> {
4488 this.update(&mut cx, |_, cx| {
4489 cx.emit(Event::Toast {
4490 notification_id: envelope.payload.notification_id.into(),
4491 message: envelope.payload.message,
4492 });
4493 Ok(())
4494 })?
4495 }
4496
4497 async fn handle_language_server_prompt_request(
4498 this: Entity<Self>,
4499 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4500 mut cx: AsyncApp,
4501 ) -> Result<proto::LanguageServerPromptResponse> {
4502 let (tx, rx) = smol::channel::bounded(1);
4503 let actions: Vec<_> = envelope
4504 .payload
4505 .actions
4506 .into_iter()
4507 .map(|action| MessageActionItem {
4508 title: action,
4509 properties: Default::default(),
4510 })
4511 .collect();
4512 this.update(&mut cx, |_, cx| {
4513 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4514 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4515 message: envelope.payload.message,
4516 actions: actions.clone(),
4517 lsp_name: envelope.payload.lsp_name,
4518 response_channel: tx,
4519 }));
4520
4521 anyhow::Ok(())
4522 })??;
4523
4524 // We drop `this` to avoid holding a reference in this future for too
4525 // long.
4526 // If we keep the reference, we might not drop the `Project` early
4527 // enough when closing a window and it will only get releases on the
4528 // next `flush_effects()` call.
4529 drop(this);
4530
4531 let mut rx = pin!(rx);
4532 let answer = rx.next().await;
4533
4534 Ok(LanguageServerPromptResponse {
4535 action_response: answer.and_then(|answer| {
4536 actions
4537 .iter()
4538 .position(|action| *action == answer)
4539 .map(|index| index as u64)
4540 }),
4541 })
4542 }
4543
4544 async fn handle_hide_toast(
4545 this: Entity<Self>,
4546 envelope: TypedEnvelope<proto::HideToast>,
4547 mut cx: AsyncApp,
4548 ) -> Result<()> {
4549 this.update(&mut cx, |_, cx| {
4550 cx.emit(Event::HideToast {
4551 notification_id: envelope.payload.notification_id.into(),
4552 });
4553 Ok(())
4554 })?
4555 }
4556
4557 // Collab sends UpdateWorktree protos as messages
4558 async fn handle_update_worktree(
4559 this: Entity<Self>,
4560 envelope: TypedEnvelope<proto::UpdateWorktree>,
4561 mut cx: AsyncApp,
4562 ) -> Result<()> {
4563 this.update(&mut cx, |this, cx| {
4564 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4565 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4566 worktree.update(cx, |worktree, _| {
4567 let worktree = worktree.as_remote_mut().unwrap();
4568 worktree.update_from_remote(envelope.payload);
4569 });
4570 }
4571 Ok(())
4572 })?
4573 }
4574
4575 async fn handle_update_buffer_from_ssh(
4576 this: Entity<Self>,
4577 envelope: TypedEnvelope<proto::UpdateBuffer>,
4578 cx: AsyncApp,
4579 ) -> Result<proto::Ack> {
4580 let buffer_store = this.read_with(&cx, |this, cx| {
4581 if let Some(remote_id) = this.remote_id() {
4582 let mut payload = envelope.payload.clone();
4583 payload.project_id = remote_id;
4584 cx.background_spawn(this.client.request(payload))
4585 .detach_and_log_err(cx);
4586 }
4587 this.buffer_store.clone()
4588 })?;
4589 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4590 }
4591
4592 async fn handle_update_buffer(
4593 this: Entity<Self>,
4594 envelope: TypedEnvelope<proto::UpdateBuffer>,
4595 cx: AsyncApp,
4596 ) -> Result<proto::Ack> {
4597 let buffer_store = this.read_with(&cx, |this, cx| {
4598 if let Some(ssh) = &this.ssh_client {
4599 let mut payload = envelope.payload.clone();
4600 payload.project_id = SSH_PROJECT_ID;
4601 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4602 .detach_and_log_err(cx);
4603 }
4604 this.buffer_store.clone()
4605 })?;
4606 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4607 }
4608
4609 fn retain_remotely_created_models(
4610 &mut self,
4611 cx: &mut Context<Self>,
4612 ) -> RemotelyCreatedModelGuard {
4613 {
4614 let mut remotely_create_models = self.remotely_created_models.lock();
4615 if remotely_create_models.retain_count == 0 {
4616 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4617 remotely_create_models.worktrees =
4618 self.worktree_store.read(cx).worktrees().collect();
4619 }
4620 remotely_create_models.retain_count += 1;
4621 }
4622 RemotelyCreatedModelGuard {
4623 remote_models: Arc::downgrade(&self.remotely_created_models),
4624 }
4625 }
4626
4627 async fn handle_create_buffer_for_peer(
4628 this: Entity<Self>,
4629 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4630 mut cx: AsyncApp,
4631 ) -> Result<()> {
4632 this.update(&mut cx, |this, cx| {
4633 this.buffer_store.update(cx, |buffer_store, cx| {
4634 buffer_store.handle_create_buffer_for_peer(
4635 envelope,
4636 this.replica_id(),
4637 this.capability(),
4638 cx,
4639 )
4640 })
4641 })?
4642 }
4643
4644 async fn handle_synchronize_buffers(
4645 this: Entity<Self>,
4646 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4647 mut cx: AsyncApp,
4648 ) -> Result<proto::SynchronizeBuffersResponse> {
4649 let response = this.update(&mut cx, |this, cx| {
4650 let client = this.client.clone();
4651 this.buffer_store.update(cx, |this, cx| {
4652 this.handle_synchronize_buffers(envelope, cx, client)
4653 })
4654 })??;
4655
4656 Ok(response)
4657 }
4658
4659 async fn handle_search_candidate_buffers(
4660 this: Entity<Self>,
4661 envelope: TypedEnvelope<proto::FindSearchCandidates>,
4662 mut cx: AsyncApp,
4663 ) -> Result<proto::FindSearchCandidatesResponse> {
4664 let peer_id = envelope.original_sender_id()?;
4665 let message = envelope.payload;
4666 let query = SearchQuery::from_proto(message.query.context("missing query field")?)?;
4667 let results = this.update(&mut cx, |this, cx| {
4668 this.find_search_candidate_buffers(&query, message.limit as _, cx)
4669 })?;
4670
4671 let mut response = proto::FindSearchCandidatesResponse {
4672 buffer_ids: Vec::new(),
4673 };
4674
4675 while let Ok(buffer) = results.recv().await {
4676 this.update(&mut cx, |this, cx| {
4677 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4678 response.buffer_ids.push(buffer_id.to_proto());
4679 })?;
4680 }
4681
4682 Ok(response)
4683 }
4684
4685 async fn handle_open_buffer_by_id(
4686 this: Entity<Self>,
4687 envelope: TypedEnvelope<proto::OpenBufferById>,
4688 mut cx: AsyncApp,
4689 ) -> Result<proto::OpenBufferResponse> {
4690 let peer_id = envelope.original_sender_id()?;
4691 let buffer_id = BufferId::new(envelope.payload.id)?;
4692 let buffer = this
4693 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4694 .await?;
4695 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4696 }
4697
4698 async fn handle_open_buffer_by_path(
4699 this: Entity<Self>,
4700 envelope: TypedEnvelope<proto::OpenBufferByPath>,
4701 mut cx: AsyncApp,
4702 ) -> Result<proto::OpenBufferResponse> {
4703 let peer_id = envelope.original_sender_id()?;
4704 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4705 let open_buffer = this.update(&mut cx, |this, cx| {
4706 this.open_buffer(
4707 ProjectPath {
4708 worktree_id,
4709 path: Arc::<Path>::from_proto(envelope.payload.path),
4710 },
4711 cx,
4712 )
4713 })?;
4714
4715 let buffer = open_buffer.await?;
4716 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4717 }
4718
4719 async fn handle_open_new_buffer(
4720 this: Entity<Self>,
4721 envelope: TypedEnvelope<proto::OpenNewBuffer>,
4722 mut cx: AsyncApp,
4723 ) -> Result<proto::OpenBufferResponse> {
4724 let buffer = this
4725 .update(&mut cx, |this, cx| this.create_buffer(cx))?
4726 .await?;
4727 let peer_id = envelope.original_sender_id()?;
4728
4729 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4730 }
4731
4732 fn respond_to_open_buffer_request(
4733 this: Entity<Self>,
4734 buffer: Entity<Buffer>,
4735 peer_id: proto::PeerId,
4736 cx: &mut AsyncApp,
4737 ) -> Result<proto::OpenBufferResponse> {
4738 this.update(cx, |this, cx| {
4739 let is_private = buffer
4740 .read(cx)
4741 .file()
4742 .map(|f| f.is_private())
4743 .unwrap_or_default();
4744 anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
4745 Ok(proto::OpenBufferResponse {
4746 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4747 })
4748 })?
4749 }
4750
4751 fn create_buffer_for_peer(
4752 &mut self,
4753 buffer: &Entity<Buffer>,
4754 peer_id: proto::PeerId,
4755 cx: &mut App,
4756 ) -> BufferId {
4757 self.buffer_store
4758 .update(cx, |buffer_store, cx| {
4759 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4760 })
4761 .detach_and_log_err(cx);
4762 buffer.read(cx).remote_id()
4763 }
4764
4765 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4766 let project_id = match self.client_state {
4767 ProjectClientState::Remote {
4768 sharing_has_stopped,
4769 remote_id,
4770 ..
4771 } => {
4772 if sharing_has_stopped {
4773 return Task::ready(Err(anyhow!(
4774 "can't synchronize remote buffers on a readonly project"
4775 )));
4776 } else {
4777 remote_id
4778 }
4779 }
4780 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4781 return Task::ready(Err(anyhow!(
4782 "can't synchronize remote buffers on a local project"
4783 )));
4784 }
4785 };
4786
4787 let client = self.client.clone();
4788 cx.spawn(async move |this, cx| {
4789 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
4790 this.buffer_store.read(cx).buffer_version_info(cx)
4791 })?;
4792 let response = client
4793 .request(proto::SynchronizeBuffers {
4794 project_id,
4795 buffers,
4796 })
4797 .await?;
4798
4799 let send_updates_for_buffers = this.update(cx, |this, cx| {
4800 response
4801 .buffers
4802 .into_iter()
4803 .map(|buffer| {
4804 let client = client.clone();
4805 let buffer_id = match BufferId::new(buffer.id) {
4806 Ok(id) => id,
4807 Err(e) => {
4808 return Task::ready(Err(e));
4809 }
4810 };
4811 let remote_version = language::proto::deserialize_version(&buffer.version);
4812 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4813 let operations =
4814 buffer.read(cx).serialize_ops(Some(remote_version), cx);
4815 cx.background_spawn(async move {
4816 let operations = operations.await;
4817 for chunk in split_operations(operations) {
4818 client
4819 .request(proto::UpdateBuffer {
4820 project_id,
4821 buffer_id: buffer_id.into(),
4822 operations: chunk,
4823 })
4824 .await?;
4825 }
4826 anyhow::Ok(())
4827 })
4828 } else {
4829 Task::ready(Ok(()))
4830 }
4831 })
4832 .collect::<Vec<_>>()
4833 })?;
4834
4835 // Any incomplete buffers have open requests waiting. Request that the host sends
4836 // creates these buffers for us again to unblock any waiting futures.
4837 for id in incomplete_buffer_ids {
4838 cx.background_spawn(client.request(proto::OpenBufferById {
4839 project_id,
4840 id: id.into(),
4841 }))
4842 .detach();
4843 }
4844
4845 futures::future::join_all(send_updates_for_buffers)
4846 .await
4847 .into_iter()
4848 .collect()
4849 })
4850 }
4851
4852 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4853 self.worktree_store.read(cx).worktree_metadata_protos(cx)
4854 }
4855
4856 /// Iterator of all open buffers that have unsaved changes
4857 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4858 self.buffer_store.read(cx).buffers().filter_map(|buf| {
4859 let buf = buf.read(cx);
4860 if buf.is_dirty() {
4861 buf.project_path(cx)
4862 } else {
4863 None
4864 }
4865 })
4866 }
4867
4868 fn set_worktrees_from_proto(
4869 &mut self,
4870 worktrees: Vec<proto::WorktreeMetadata>,
4871 cx: &mut Context<Project>,
4872 ) -> Result<()> {
4873 self.worktree_store.update(cx, |worktree_store, cx| {
4874 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4875 })
4876 }
4877
4878 fn set_collaborators_from_proto(
4879 &mut self,
4880 messages: Vec<proto::Collaborator>,
4881 cx: &mut Context<Self>,
4882 ) -> Result<()> {
4883 let mut collaborators = HashMap::default();
4884 for message in messages {
4885 let collaborator = Collaborator::from_proto(message)?;
4886 collaborators.insert(collaborator.peer_id, collaborator);
4887 }
4888 for old_peer_id in self.collaborators.keys() {
4889 if !collaborators.contains_key(old_peer_id) {
4890 cx.emit(Event::CollaboratorLeft(*old_peer_id));
4891 }
4892 }
4893 self.collaborators = collaborators;
4894 Ok(())
4895 }
4896
4897 pub fn supplementary_language_servers<'a>(
4898 &'a self,
4899 cx: &'a App,
4900 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4901 self.lsp_store.read(cx).supplementary_language_servers()
4902 }
4903
4904 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4905 self.lsp_store.update(cx, |this, cx| {
4906 this.language_servers_for_local_buffer(buffer, cx)
4907 .any(
4908 |(_, server)| match server.capabilities().inlay_hint_provider {
4909 Some(lsp::OneOf::Left(enabled)) => enabled,
4910 Some(lsp::OneOf::Right(_)) => true,
4911 None => false,
4912 },
4913 )
4914 })
4915 }
4916
4917 pub fn language_server_id_for_name(
4918 &self,
4919 buffer: &Buffer,
4920 name: &str,
4921 cx: &mut App,
4922 ) -> Task<Option<LanguageServerId>> {
4923 if self.is_local() {
4924 Task::ready(self.lsp_store.update(cx, |lsp_store, cx| {
4925 lsp_store
4926 .language_servers_for_local_buffer(buffer, cx)
4927 .find_map(|(adapter, server)| {
4928 if adapter.name.0 == name {
4929 Some(server.server_id())
4930 } else {
4931 None
4932 }
4933 })
4934 }))
4935 } else if let Some(project_id) = self.remote_id() {
4936 let request = self.client.request(proto::LanguageServerIdForName {
4937 project_id,
4938 buffer_id: buffer.remote_id().to_proto(),
4939 name: name.to_string(),
4940 });
4941 cx.background_spawn(async move {
4942 let response = request.await.log_err()?;
4943 response.server_id.map(LanguageServerId::from_proto)
4944 })
4945 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
4946 let request =
4947 ssh_client
4948 .read(cx)
4949 .proto_client()
4950 .request(proto::LanguageServerIdForName {
4951 project_id: SSH_PROJECT_ID,
4952 buffer_id: buffer.remote_id().to_proto(),
4953 name: name.to_string(),
4954 });
4955 cx.background_spawn(async move {
4956 let response = request.await.log_err()?;
4957 response.server_id.map(LanguageServerId::from_proto)
4958 })
4959 } else {
4960 Task::ready(None)
4961 }
4962 }
4963
4964 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
4965 self.lsp_store.update(cx, |this, cx| {
4966 this.language_servers_for_local_buffer(buffer, cx)
4967 .next()
4968 .is_some()
4969 })
4970 }
4971
4972 pub fn git_init(
4973 &self,
4974 path: Arc<Path>,
4975 fallback_branch_name: String,
4976 cx: &App,
4977 ) -> Task<Result<()>> {
4978 self.git_store
4979 .read(cx)
4980 .git_init(path, fallback_branch_name, cx)
4981 }
4982
4983 pub fn buffer_store(&self) -> &Entity<BufferStore> {
4984 &self.buffer_store
4985 }
4986
4987 pub fn git_store(&self) -> &Entity<GitStore> {
4988 &self.git_store
4989 }
4990
4991 #[cfg(test)]
4992 fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
4993 cx.spawn(async move |this, cx| {
4994 let scans_complete = this
4995 .read_with(cx, |this, cx| {
4996 this.worktrees(cx)
4997 .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
4998 .collect::<Vec<_>>()
4999 })
5000 .unwrap();
5001 join_all(scans_complete).await;
5002 let barriers = this
5003 .update(cx, |this, cx| {
5004 let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
5005 repos
5006 .into_iter()
5007 .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
5008 .collect::<Vec<_>>()
5009 })
5010 .unwrap();
5011 join_all(barriers).await;
5012 })
5013 }
5014
5015 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
5016 self.git_store.read(cx).active_repository()
5017 }
5018
5019 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
5020 self.git_store.read(cx).repositories()
5021 }
5022
5023 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
5024 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
5025 }
5026
5027 pub fn set_agent_location(
5028 &mut self,
5029 new_location: Option<AgentLocation>,
5030 cx: &mut Context<Self>,
5031 ) {
5032 if let Some(old_location) = self.agent_location.as_ref() {
5033 old_location
5034 .buffer
5035 .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
5036 .ok();
5037 }
5038
5039 if let Some(location) = new_location.as_ref() {
5040 location
5041 .buffer
5042 .update(cx, |buffer, cx| {
5043 buffer.set_agent_selections(
5044 Arc::from([language::Selection {
5045 id: 0,
5046 start: location.position,
5047 end: location.position,
5048 reversed: false,
5049 goal: language::SelectionGoal::None,
5050 }]),
5051 false,
5052 CursorShape::Hollow,
5053 cx,
5054 )
5055 })
5056 .ok();
5057 }
5058
5059 self.agent_location = new_location;
5060 cx.emit(Event::AgentLocationChanged);
5061 }
5062
5063 pub fn agent_location(&self) -> Option<AgentLocation> {
5064 self.agent_location.clone()
5065 }
5066
5067 pub fn mark_buffer_as_non_searchable(&self, buffer_id: BufferId, cx: &mut Context<Project>) {
5068 self.buffer_store.update(cx, |buffer_store, _| {
5069 buffer_store.mark_buffer_as_non_searchable(buffer_id)
5070 });
5071 }
5072}
5073
5074pub struct PathMatchCandidateSet {
5075 pub snapshot: Snapshot,
5076 pub include_ignored: bool,
5077 pub include_root_name: bool,
5078 pub candidates: Candidates,
5079}
5080
5081pub enum Candidates {
5082 /// Only consider directories.
5083 Directories,
5084 /// Only consider files.
5085 Files,
5086 /// Consider directories and files.
5087 Entries,
5088}
5089
5090impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5091 type Candidates = PathMatchCandidateSetIter<'a>;
5092
5093 fn id(&self) -> usize {
5094 self.snapshot.id().to_usize()
5095 }
5096
5097 fn len(&self) -> usize {
5098 match self.candidates {
5099 Candidates::Files => {
5100 if self.include_ignored {
5101 self.snapshot.file_count()
5102 } else {
5103 self.snapshot.visible_file_count()
5104 }
5105 }
5106
5107 Candidates::Directories => {
5108 if self.include_ignored {
5109 self.snapshot.dir_count()
5110 } else {
5111 self.snapshot.visible_dir_count()
5112 }
5113 }
5114
5115 Candidates::Entries => {
5116 if self.include_ignored {
5117 self.snapshot.entry_count()
5118 } else {
5119 self.snapshot.visible_entry_count()
5120 }
5121 }
5122 }
5123 }
5124
5125 fn prefix(&self) -> Arc<str> {
5126 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5127 self.snapshot.root_name().into()
5128 } else if self.include_root_name {
5129 format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
5130 } else {
5131 Arc::default()
5132 }
5133 }
5134
5135 fn candidates(&'a self, start: usize) -> Self::Candidates {
5136 PathMatchCandidateSetIter {
5137 traversal: match self.candidates {
5138 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5139 Candidates::Files => self.snapshot.files(self.include_ignored, start),
5140 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5141 },
5142 }
5143 }
5144}
5145
5146pub struct PathMatchCandidateSetIter<'a> {
5147 traversal: Traversal<'a>,
5148}
5149
5150impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5151 type Item = fuzzy::PathMatchCandidate<'a>;
5152
5153 fn next(&mut self) -> Option<Self::Item> {
5154 self.traversal
5155 .next()
5156 .map(|entry| fuzzy::PathMatchCandidate {
5157 is_dir: entry.kind.is_dir(),
5158 path: &entry.path,
5159 char_bag: entry.char_bag,
5160 })
5161 }
5162}
5163
5164impl EventEmitter<Event> for Project {}
5165
5166impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5167 fn from(val: &'a ProjectPath) -> Self {
5168 SettingsLocation {
5169 worktree_id: val.worktree_id,
5170 path: val.path.as_ref(),
5171 }
5172 }
5173}
5174
5175impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5176 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5177 Self {
5178 worktree_id,
5179 path: path.as_ref().into(),
5180 }
5181 }
5182}
5183
5184pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5185 let mut path_components = path.components();
5186 let mut base_components = base.components();
5187 let mut components: Vec<Component> = Vec::new();
5188 loop {
5189 match (path_components.next(), base_components.next()) {
5190 (None, None) => break,
5191 (Some(a), None) => {
5192 components.push(a);
5193 components.extend(path_components.by_ref());
5194 break;
5195 }
5196 (None, _) => components.push(Component::ParentDir),
5197 (Some(a), Some(b)) if components.is_empty() && a == b => (),
5198 (Some(a), Some(Component::CurDir)) => components.push(a),
5199 (Some(a), Some(_)) => {
5200 components.push(Component::ParentDir);
5201 for _ in base_components {
5202 components.push(Component::ParentDir);
5203 }
5204 components.push(a);
5205 components.extend(path_components.by_ref());
5206 break;
5207 }
5208 }
5209 }
5210 components.iter().map(|c| c.as_os_str()).collect()
5211}
5212
5213fn resolve_path(base: &Path, path: &Path) -> PathBuf {
5214 let mut result = base.to_path_buf();
5215 for component in path.components() {
5216 match component {
5217 Component::ParentDir => {
5218 result.pop();
5219 }
5220 Component::CurDir => (),
5221 _ => result.push(component),
5222 }
5223 }
5224 result
5225}
5226
5227/// ResolvedPath is a path that has been resolved to either a ProjectPath
5228/// or an AbsPath and that *exists*.
5229#[derive(Debug, Clone)]
5230pub enum ResolvedPath {
5231 ProjectPath {
5232 project_path: ProjectPath,
5233 is_dir: bool,
5234 },
5235 AbsPath {
5236 path: PathBuf,
5237 is_dir: bool,
5238 },
5239}
5240
5241impl ResolvedPath {
5242 pub fn abs_path(&self) -> Option<&Path> {
5243 match self {
5244 Self::AbsPath { path, .. } => Some(path.as_path()),
5245 _ => None,
5246 }
5247 }
5248
5249 pub fn into_abs_path(self) -> Option<PathBuf> {
5250 match self {
5251 Self::AbsPath { path, .. } => Some(path),
5252 _ => None,
5253 }
5254 }
5255
5256 pub fn project_path(&self) -> Option<&ProjectPath> {
5257 match self {
5258 Self::ProjectPath { project_path, .. } => Some(&project_path),
5259 _ => None,
5260 }
5261 }
5262
5263 pub fn is_file(&self) -> bool {
5264 !self.is_dir()
5265 }
5266
5267 pub fn is_dir(&self) -> bool {
5268 match self {
5269 Self::ProjectPath { is_dir, .. } => *is_dir,
5270 Self::AbsPath { is_dir, .. } => *is_dir,
5271 }
5272 }
5273}
5274
5275impl ProjectItem for Buffer {
5276 fn try_open(
5277 project: &Entity<Project>,
5278 path: &ProjectPath,
5279 cx: &mut App,
5280 ) -> Option<Task<Result<Entity<Self>>>> {
5281 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5282 }
5283
5284 fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
5285 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5286 }
5287
5288 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5289 self.file().map(|file| ProjectPath {
5290 worktree_id: file.worktree_id(cx),
5291 path: file.path().clone(),
5292 })
5293 }
5294
5295 fn is_dirty(&self) -> bool {
5296 self.is_dirty()
5297 }
5298}
5299
5300impl Completion {
5301 pub fn kind(&self) -> Option<CompletionItemKind> {
5302 self.source
5303 // `lsp::CompletionListItemDefaults` has no `kind` field
5304 .lsp_completion(false)
5305 .and_then(|lsp_completion| lsp_completion.kind)
5306 }
5307
5308 pub fn label(&self) -> Option<String> {
5309 self.source
5310 .lsp_completion(false)
5311 .map(|lsp_completion| lsp_completion.label.clone())
5312 }
5313
5314 /// A key that can be used to sort completions when displaying
5315 /// them to the user.
5316 pub fn sort_key(&self) -> (usize, &str) {
5317 const DEFAULT_KIND_KEY: usize = 4;
5318 let kind_key = self
5319 .kind()
5320 .and_then(|lsp_completion_kind| match lsp_completion_kind {
5321 lsp::CompletionItemKind::KEYWORD => Some(0),
5322 lsp::CompletionItemKind::VARIABLE => Some(1),
5323 lsp::CompletionItemKind::CONSTANT => Some(2),
5324 lsp::CompletionItemKind::PROPERTY => Some(3),
5325 _ => None,
5326 })
5327 .unwrap_or(DEFAULT_KIND_KEY);
5328 (kind_key, &self.label.filter_text())
5329 }
5330
5331 /// Whether this completion is a snippet.
5332 pub fn is_snippet(&self) -> bool {
5333 self.source
5334 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5335 .lsp_completion(true)
5336 .map_or(false, |lsp_completion| {
5337 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5338 })
5339 }
5340
5341 /// Returns the corresponding color for this completion.
5342 ///
5343 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5344 pub fn color(&self) -> Option<Hsla> {
5345 // `lsp::CompletionListItemDefaults` has no `kind` field
5346 let lsp_completion = self.source.lsp_completion(false)?;
5347 if lsp_completion.kind? == CompletionItemKind::COLOR {
5348 return color_extractor::extract_color(&lsp_completion);
5349 }
5350 None
5351 }
5352}
5353
5354pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
5355 entries.sort_by(|entry_a, entry_b| {
5356 let entry_a = entry_a.as_ref();
5357 let entry_b = entry_b.as_ref();
5358 compare_paths(
5359 (&entry_a.path, entry_a.is_file()),
5360 (&entry_b.path, entry_b.is_file()),
5361 )
5362 });
5363}
5364
5365fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5366 match level {
5367 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5368 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5369 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5370 }
5371}
5372
5373fn provide_inline_values(
5374 captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
5375 snapshot: &language::BufferSnapshot,
5376 max_row: usize,
5377) -> Vec<InlineValueLocation> {
5378 let mut variables = Vec::new();
5379 let mut variable_position = HashSet::default();
5380 let mut scopes = Vec::new();
5381
5382 let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
5383
5384 for (capture_range, capture_kind) in captures {
5385 match capture_kind {
5386 language::DebuggerTextObject::Variable => {
5387 let variable_name = snapshot
5388 .text_for_range(capture_range.clone())
5389 .collect::<String>();
5390 let point = snapshot.offset_to_point(capture_range.end);
5391
5392 while scopes.last().map_or(false, |scope: &Range<_>| {
5393 !scope.contains(&capture_range.start)
5394 }) {
5395 scopes.pop();
5396 }
5397
5398 if point.row as usize > max_row {
5399 break;
5400 }
5401
5402 let scope = if scopes
5403 .last()
5404 .map_or(true, |scope| !scope.contains(&active_debug_line_offset))
5405 {
5406 VariableScope::Global
5407 } else {
5408 VariableScope::Local
5409 };
5410
5411 if variable_position.insert(capture_range.end) {
5412 variables.push(InlineValueLocation {
5413 variable_name,
5414 scope,
5415 lookup: VariableLookupKind::Variable,
5416 row: point.row as usize,
5417 column: point.column as usize,
5418 });
5419 }
5420 }
5421 language::DebuggerTextObject::Scope => {
5422 while scopes.last().map_or_else(
5423 || false,
5424 |scope: &Range<usize>| {
5425 !(scope.contains(&capture_range.start)
5426 && scope.contains(&capture_range.end))
5427 },
5428 ) {
5429 scopes.pop();
5430 }
5431 scopes.push(capture_range);
5432 }
5433 }
5434 }
5435
5436 variables
5437}