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