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