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