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