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::new();
3666 for buffer in matching_buffer_chunk {
3667 let buffer = buffer.clone();
3668 let query = query.clone();
3669 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
3670 chunk_results.push(cx.background_spawn(async move {
3671 let ranges = query
3672 .search(&snapshot, None)
3673 .await
3674 .iter()
3675 .map(|range| {
3676 snapshot.anchor_before(range.start)
3677 ..snapshot.anchor_after(range.end)
3678 })
3679 .collect::<Vec<_>>();
3680 anyhow::Ok((buffer, ranges))
3681 }));
3682 }
3683
3684 let chunk_results = futures::future::join_all(chunk_results).await;
3685 for result in chunk_results {
3686 if let Some((buffer, ranges)) = result.log_err() {
3687 range_count += ranges.len();
3688 buffer_count += 1;
3689 result_tx
3690 .send(SearchResult::Buffer { buffer, ranges })
3691 .await?;
3692 if buffer_count > MAX_SEARCH_RESULT_FILES
3693 || range_count > MAX_SEARCH_RESULT_RANGES
3694 {
3695 limit_reached = true;
3696 break 'outer;
3697 }
3698 }
3699 }
3700 }
3701
3702 if limit_reached {
3703 result_tx.send(SearchResult::LimitReached).await?;
3704 }
3705
3706 anyhow::Ok(())
3707 })
3708 .detach();
3709
3710 result_rx
3711 }
3712
3713 fn find_search_candidate_buffers(
3714 &mut self,
3715 query: &SearchQuery,
3716 limit: usize,
3717 cx: &mut Context<Project>,
3718 ) -> Receiver<Entity<Buffer>> {
3719 if self.is_local() {
3720 let fs = self.fs.clone();
3721 self.buffer_store.update(cx, |buffer_store, cx| {
3722 buffer_store.find_search_candidates(query, limit, fs, cx)
3723 })
3724 } else {
3725 self.find_search_candidates_remote(query, limit, cx)
3726 }
3727 }
3728
3729 fn sort_search_candidates(
3730 &mut self,
3731 search_query: &SearchQuery,
3732 cx: &mut Context<Project>,
3733 ) -> Receiver<Entity<Buffer>> {
3734 let worktree_store = self.worktree_store.read(cx);
3735 let mut buffers = search_query
3736 .buffers()
3737 .into_iter()
3738 .flatten()
3739 .filter(|buffer| {
3740 let b = buffer.read(cx);
3741 if let Some(file) = b.file() {
3742 if !search_query.match_path(file.path()) {
3743 return false;
3744 }
3745 if let Some(entry) = b
3746 .entry_id(cx)
3747 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3748 {
3749 if entry.is_ignored && !search_query.include_ignored() {
3750 return false;
3751 }
3752 }
3753 }
3754 true
3755 })
3756 .collect::<Vec<_>>();
3757 let (tx, rx) = smol::channel::unbounded();
3758 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3759 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3760 (None, Some(_)) => std::cmp::Ordering::Less,
3761 (Some(_), None) => std::cmp::Ordering::Greater,
3762 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3763 });
3764 for buffer in buffers {
3765 tx.send_blocking(buffer.clone()).unwrap()
3766 }
3767
3768 rx
3769 }
3770
3771 fn find_search_candidates_remote(
3772 &mut self,
3773 query: &SearchQuery,
3774 limit: usize,
3775 cx: &mut Context<Project>,
3776 ) -> Receiver<Entity<Buffer>> {
3777 let (tx, rx) = smol::channel::unbounded();
3778
3779 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3780 (ssh_client.read(cx).proto_client(), 0)
3781 } else if let Some(remote_id) = self.remote_id() {
3782 (self.client.clone().into(), remote_id)
3783 } else {
3784 return rx;
3785 };
3786
3787 let request = client.request(proto::FindSearchCandidates {
3788 project_id: remote_id,
3789 query: Some(query.to_proto()),
3790 limit: limit as _,
3791 });
3792 let guard = self.retain_remotely_created_models(cx);
3793
3794 cx.spawn(async move |project, cx| {
3795 let response = request.await?;
3796 for buffer_id in response.buffer_ids {
3797 let buffer_id = BufferId::new(buffer_id)?;
3798 let buffer = project
3799 .update(cx, |project, cx| {
3800 project.buffer_store.update(cx, |buffer_store, cx| {
3801 buffer_store.wait_for_remote_buffer(buffer_id, cx)
3802 })
3803 })?
3804 .await?;
3805 let _ = tx.send(buffer).await;
3806 }
3807
3808 drop(guard);
3809 anyhow::Ok(())
3810 })
3811 .detach_and_log_err(cx);
3812 rx
3813 }
3814
3815 pub fn request_lsp<R: LspCommand>(
3816 &mut self,
3817 buffer_handle: Entity<Buffer>,
3818 server: LanguageServerToQuery,
3819 request: R,
3820 cx: &mut Context<Self>,
3821 ) -> Task<Result<R::Response>>
3822 where
3823 <R::LspRequest as lsp::request::Request>::Result: Send,
3824 <R::LspRequest as lsp::request::Request>::Params: Send,
3825 {
3826 let guard = self.retain_remotely_created_models(cx);
3827 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3828 lsp_store.request_lsp(buffer_handle, server, request, cx)
3829 });
3830 cx.spawn(async move |_, _| {
3831 let result = task.await;
3832 drop(guard);
3833 result
3834 })
3835 }
3836
3837 /// Move a worktree to a new position in the worktree order.
3838 ///
3839 /// The worktree will moved to the opposite side of the destination worktree.
3840 ///
3841 /// # Example
3842 ///
3843 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3844 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3845 ///
3846 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3847 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3848 ///
3849 /// # Errors
3850 ///
3851 /// An error will be returned if the worktree or destination worktree are not found.
3852 pub fn move_worktree(
3853 &mut self,
3854 source: WorktreeId,
3855 destination: WorktreeId,
3856 cx: &mut Context<Self>,
3857 ) -> Result<()> {
3858 self.worktree_store.update(cx, |worktree_store, cx| {
3859 worktree_store.move_worktree(source, destination, cx)
3860 })
3861 }
3862
3863 pub fn find_or_create_worktree(
3864 &mut self,
3865 abs_path: impl AsRef<Path>,
3866 visible: bool,
3867 cx: &mut Context<Self>,
3868 ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3869 self.worktree_store.update(cx, |worktree_store, cx| {
3870 worktree_store.find_or_create_worktree(abs_path, visible, cx)
3871 })
3872 }
3873
3874 pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3875 self.worktree_store.read_with(cx, |worktree_store, cx| {
3876 worktree_store.find_worktree(abs_path, cx)
3877 })
3878 }
3879
3880 pub fn is_shared(&self) -> bool {
3881 match &self.client_state {
3882 ProjectClientState::Shared { .. } => true,
3883 ProjectClientState::Local => false,
3884 ProjectClientState::Remote { .. } => true,
3885 }
3886 }
3887
3888 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3889 pub fn resolve_path_in_buffer(
3890 &self,
3891 path: &str,
3892 buffer: &Entity<Buffer>,
3893 cx: &mut Context<Self>,
3894 ) -> Task<Option<ResolvedPath>> {
3895 let path_buf = PathBuf::from(path);
3896 if path_buf.is_absolute() || path.starts_with("~") {
3897 self.resolve_abs_path(path, cx)
3898 } else {
3899 self.resolve_path_in_worktrees(path_buf, buffer, cx)
3900 }
3901 }
3902
3903 pub fn resolve_abs_file_path(
3904 &self,
3905 path: &str,
3906 cx: &mut Context<Self>,
3907 ) -> Task<Option<ResolvedPath>> {
3908 let resolve_task = self.resolve_abs_path(path, cx);
3909 cx.background_spawn(async move {
3910 let resolved_path = resolve_task.await;
3911 resolved_path.filter(|path| path.is_file())
3912 })
3913 }
3914
3915 pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
3916 if self.is_local() {
3917 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3918 let fs = self.fs.clone();
3919 cx.background_spawn(async move {
3920 let path = expanded.as_path();
3921 let metadata = fs.metadata(path).await.ok().flatten();
3922
3923 metadata.map(|metadata| ResolvedPath::AbsPath {
3924 path: expanded,
3925 is_dir: metadata.is_dir,
3926 })
3927 })
3928 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3929 let request_path = Path::new(path);
3930 let request = ssh_client
3931 .read(cx)
3932 .proto_client()
3933 .request(proto::GetPathMetadata {
3934 project_id: SSH_PROJECT_ID,
3935 path: request_path.to_proto(),
3936 });
3937 cx.background_spawn(async move {
3938 let response = request.await.log_err()?;
3939 if response.exists {
3940 Some(ResolvedPath::AbsPath {
3941 path: PathBuf::from_proto(response.path),
3942 is_dir: response.is_dir,
3943 })
3944 } else {
3945 None
3946 }
3947 })
3948 } else {
3949 return Task::ready(None);
3950 }
3951 }
3952
3953 fn resolve_path_in_worktrees(
3954 &self,
3955 path: PathBuf,
3956 buffer: &Entity<Buffer>,
3957 cx: &mut Context<Self>,
3958 ) -> Task<Option<ResolvedPath>> {
3959 let mut candidates = vec![path.clone()];
3960
3961 if let Some(file) = buffer.read(cx).file() {
3962 if let Some(dir) = file.path().parent() {
3963 let joined = dir.to_path_buf().join(path);
3964 candidates.push(joined);
3965 }
3966 }
3967
3968 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
3969 let worktrees_with_ids: Vec<_> = self
3970 .worktrees(cx)
3971 .map(|worktree| {
3972 let id = worktree.read(cx).id();
3973 (worktree, id)
3974 })
3975 .collect();
3976
3977 cx.spawn(async move |_, mut cx| {
3978 if let Some(buffer_worktree_id) = buffer_worktree_id {
3979 if let Some((worktree, _)) = worktrees_with_ids
3980 .iter()
3981 .find(|(_, id)| *id == buffer_worktree_id)
3982 {
3983 for candidate in candidates.iter() {
3984 if let Some(path) =
3985 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3986 {
3987 return Some(path);
3988 }
3989 }
3990 }
3991 }
3992 for (worktree, id) in worktrees_with_ids {
3993 if Some(id) == buffer_worktree_id {
3994 continue;
3995 }
3996 for candidate in candidates.iter() {
3997 if let Some(path) =
3998 Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3999 {
4000 return Some(path);
4001 }
4002 }
4003 }
4004 None
4005 })
4006 }
4007
4008 fn resolve_path_in_worktree(
4009 worktree: &Entity<Worktree>,
4010 path: &PathBuf,
4011 cx: &mut AsyncApp,
4012 ) -> Option<ResolvedPath> {
4013 worktree
4014 .update(cx, |worktree, _| {
4015 let root_entry_path = &worktree.root_entry()?.path;
4016 let resolved = resolve_path(root_entry_path, path);
4017 let stripped = resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
4018 worktree.entry_for_path(stripped).map(|entry| {
4019 let project_path = ProjectPath {
4020 worktree_id: worktree.id(),
4021 path: entry.path.clone(),
4022 };
4023 ResolvedPath::ProjectPath {
4024 project_path,
4025 is_dir: entry.is_dir(),
4026 }
4027 })
4028 })
4029 .ok()?
4030 }
4031
4032 pub fn list_directory(
4033 &self,
4034 query: String,
4035 cx: &mut Context<Self>,
4036 ) -> Task<Result<Vec<DirectoryItem>>> {
4037 if self.is_local() {
4038 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
4039 } else if let Some(session) = self.ssh_client.as_ref() {
4040 let path_buf = PathBuf::from(query);
4041 let request = proto::ListRemoteDirectory {
4042 dev_server_id: SSH_PROJECT_ID,
4043 path: path_buf.to_proto(),
4044 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4045 };
4046
4047 let response = session.read(cx).proto_client().request(request);
4048 cx.background_spawn(async move {
4049 let proto::ListRemoteDirectoryResponse {
4050 entries,
4051 entry_info,
4052 } = response.await?;
4053 Ok(entries
4054 .into_iter()
4055 .zip(entry_info)
4056 .map(|(entry, info)| DirectoryItem {
4057 path: PathBuf::from(entry),
4058 is_dir: info.is_dir,
4059 })
4060 .collect())
4061 })
4062 } else {
4063 Task::ready(Err(anyhow!("cannot list directory in remote project")))
4064 }
4065 }
4066
4067 pub fn create_worktree(
4068 &mut self,
4069 abs_path: impl AsRef<Path>,
4070 visible: bool,
4071 cx: &mut Context<Self>,
4072 ) -> Task<Result<Entity<Worktree>>> {
4073 self.worktree_store.update(cx, |worktree_store, cx| {
4074 worktree_store.create_worktree(abs_path, visible, cx)
4075 })
4076 }
4077
4078 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4079 self.worktree_store.update(cx, |worktree_store, cx| {
4080 worktree_store.remove_worktree(id_to_remove, cx);
4081 });
4082 }
4083
4084 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4085 self.worktree_store.update(cx, |worktree_store, cx| {
4086 worktree_store.add(worktree, cx);
4087 });
4088 }
4089
4090 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4091 let new_active_entry = entry.and_then(|project_path| {
4092 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4093 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4094 Some(entry.id)
4095 });
4096 if new_active_entry != self.active_entry {
4097 self.active_entry = new_active_entry;
4098 self.lsp_store.update(cx, |lsp_store, _| {
4099 lsp_store.set_active_entry(new_active_entry);
4100 });
4101 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4102 }
4103 }
4104
4105 pub fn language_servers_running_disk_based_diagnostics<'a>(
4106 &'a self,
4107 cx: &'a App,
4108 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4109 self.lsp_store
4110 .read(cx)
4111 .language_servers_running_disk_based_diagnostics()
4112 }
4113
4114 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4115 self.lsp_store
4116 .read(cx)
4117 .diagnostic_summary(include_ignored, cx)
4118 }
4119
4120 pub fn diagnostic_summaries<'a>(
4121 &'a self,
4122 include_ignored: bool,
4123 cx: &'a App,
4124 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4125 self.lsp_store
4126 .read(cx)
4127 .diagnostic_summaries(include_ignored, cx)
4128 }
4129
4130 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4131 self.active_entry
4132 }
4133
4134 pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
4135 self.worktree_store.read(cx).entry_for_path(path, cx)
4136 }
4137
4138 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4139 let worktree = self.worktree_for_entry(entry_id, cx)?;
4140 let worktree = worktree.read(cx);
4141 let worktree_id = worktree.id();
4142 let path = worktree.entry_for_id(entry_id)?.path.clone();
4143 Some(ProjectPath { worktree_id, path })
4144 }
4145
4146 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4147 self.worktree_for_id(project_path.worktree_id, cx)?
4148 .read(cx)
4149 .absolutize(&project_path.path)
4150 .ok()
4151 }
4152
4153 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4154 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4155 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4156 /// the first visible worktree that has an entry for that relative path.
4157 ///
4158 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4159 /// root name from paths.
4160 ///
4161 /// # Arguments
4162 ///
4163 /// * `path` - A full path that starts with a worktree root name, or alternatively a
4164 /// relative path within a visible worktree.
4165 /// * `cx` - A reference to the `AppContext`.
4166 ///
4167 /// # Returns
4168 ///
4169 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4170 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4171 let path = path.as_ref();
4172 let worktree_store = self.worktree_store.read(cx);
4173
4174 if path.is_absolute() {
4175 for worktree in worktree_store.visible_worktrees(cx) {
4176 let worktree_abs_path = worktree.read(cx).abs_path();
4177
4178 if let Ok(relative_path) = path.strip_prefix(worktree_abs_path) {
4179 return Some(ProjectPath {
4180 worktree_id: worktree.read(cx).id(),
4181 path: relative_path.into(),
4182 });
4183 }
4184 }
4185 } else {
4186 for worktree in worktree_store.visible_worktrees(cx) {
4187 let worktree_root_name = worktree.read(cx).root_name();
4188 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
4189 return Some(ProjectPath {
4190 worktree_id: worktree.read(cx).id(),
4191 path: relative_path.into(),
4192 });
4193 }
4194 }
4195
4196 for worktree in worktree_store.visible_worktrees(cx) {
4197 let worktree = worktree.read(cx);
4198 if let Some(entry) = worktree.entry_for_path(path) {
4199 return Some(ProjectPath {
4200 worktree_id: worktree.id(),
4201 path: entry.path.clone(),
4202 });
4203 }
4204 }
4205 }
4206
4207 None
4208 }
4209
4210 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4211 self.find_worktree(abs_path, cx)
4212 .map(|(worktree, relative_path)| ProjectPath {
4213 worktree_id: worktree.read(cx).id(),
4214 path: relative_path.into(),
4215 })
4216 }
4217
4218 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4219 Some(
4220 self.worktree_for_id(project_path.worktree_id, cx)?
4221 .read(cx)
4222 .abs_path()
4223 .to_path_buf(),
4224 )
4225 }
4226
4227 pub fn blame_buffer(
4228 &self,
4229 buffer: &Entity<Buffer>,
4230 version: Option<clock::Global>,
4231 cx: &mut App,
4232 ) -> Task<Result<Option<Blame>>> {
4233 self.git_store.update(cx, |git_store, cx| {
4234 git_store.blame_buffer(buffer, version, cx)
4235 })
4236 }
4237
4238 pub fn get_permalink_to_line(
4239 &self,
4240 buffer: &Entity<Buffer>,
4241 selection: Range<u32>,
4242 cx: &mut App,
4243 ) -> Task<Result<url::Url>> {
4244 self.git_store.update(cx, |git_store, cx| {
4245 git_store.get_permalink_to_line(buffer, selection, cx)
4246 })
4247 }
4248
4249 // RPC message handlers
4250
4251 async fn handle_unshare_project(
4252 this: Entity<Self>,
4253 _: TypedEnvelope<proto::UnshareProject>,
4254 mut cx: AsyncApp,
4255 ) -> Result<()> {
4256 this.update(&mut cx, |this, cx| {
4257 if this.is_local() || this.is_via_ssh() {
4258 this.unshare(cx)?;
4259 } else {
4260 this.disconnected_from_host(cx);
4261 }
4262 Ok(())
4263 })?
4264 }
4265
4266 async fn handle_add_collaborator(
4267 this: Entity<Self>,
4268 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4269 mut cx: AsyncApp,
4270 ) -> Result<()> {
4271 let collaborator = envelope
4272 .payload
4273 .collaborator
4274 .take()
4275 .context("empty collaborator")?;
4276
4277 let collaborator = Collaborator::from_proto(collaborator)?;
4278 this.update(&mut cx, |this, cx| {
4279 this.buffer_store.update(cx, |buffer_store, _| {
4280 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4281 });
4282 this.breakpoint_store.read(cx).broadcast();
4283 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4284 this.collaborators
4285 .insert(collaborator.peer_id, collaborator);
4286 })?;
4287
4288 Ok(())
4289 }
4290
4291 async fn handle_update_project_collaborator(
4292 this: Entity<Self>,
4293 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4294 mut cx: AsyncApp,
4295 ) -> Result<()> {
4296 let old_peer_id = envelope
4297 .payload
4298 .old_peer_id
4299 .context("missing old peer id")?;
4300 let new_peer_id = envelope
4301 .payload
4302 .new_peer_id
4303 .context("missing new peer id")?;
4304 this.update(&mut cx, |this, cx| {
4305 let collaborator = this
4306 .collaborators
4307 .remove(&old_peer_id)
4308 .context("received UpdateProjectCollaborator for unknown peer")?;
4309 let is_host = collaborator.is_host;
4310 this.collaborators.insert(new_peer_id, collaborator);
4311
4312 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4313 this.buffer_store.update(cx, |buffer_store, _| {
4314 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4315 });
4316
4317 if is_host {
4318 this.buffer_store
4319 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4320 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4321 .unwrap();
4322 cx.emit(Event::HostReshared);
4323 }
4324
4325 cx.emit(Event::CollaboratorUpdated {
4326 old_peer_id,
4327 new_peer_id,
4328 });
4329 Ok(())
4330 })?
4331 }
4332
4333 async fn handle_remove_collaborator(
4334 this: Entity<Self>,
4335 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4336 mut cx: AsyncApp,
4337 ) -> Result<()> {
4338 this.update(&mut cx, |this, cx| {
4339 let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4340 let replica_id = this
4341 .collaborators
4342 .remove(&peer_id)
4343 .with_context(|| format!("unknown peer {peer_id:?}"))?
4344 .replica_id;
4345 this.buffer_store.update(cx, |buffer_store, cx| {
4346 buffer_store.forget_shared_buffers_for(&peer_id);
4347 for buffer in buffer_store.buffers() {
4348 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4349 }
4350 });
4351 this.git_store.update(cx, |git_store, _| {
4352 git_store.forget_shared_diffs_for(&peer_id);
4353 });
4354
4355 cx.emit(Event::CollaboratorLeft(peer_id));
4356 Ok(())
4357 })?
4358 }
4359
4360 async fn handle_update_project(
4361 this: Entity<Self>,
4362 envelope: TypedEnvelope<proto::UpdateProject>,
4363 mut cx: AsyncApp,
4364 ) -> Result<()> {
4365 this.update(&mut cx, |this, cx| {
4366 // Don't handle messages that were sent before the response to us joining the project
4367 if envelope.message_id > this.join_project_response_message_id {
4368 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4369 }
4370 Ok(())
4371 })?
4372 }
4373
4374 async fn handle_toast(
4375 this: Entity<Self>,
4376 envelope: TypedEnvelope<proto::Toast>,
4377 mut cx: AsyncApp,
4378 ) -> Result<()> {
4379 this.update(&mut cx, |_, cx| {
4380 cx.emit(Event::Toast {
4381 notification_id: envelope.payload.notification_id.into(),
4382 message: envelope.payload.message,
4383 });
4384 Ok(())
4385 })?
4386 }
4387
4388 async fn handle_language_server_prompt_request(
4389 this: Entity<Self>,
4390 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4391 mut cx: AsyncApp,
4392 ) -> Result<proto::LanguageServerPromptResponse> {
4393 let (tx, rx) = smol::channel::bounded(1);
4394 let actions: Vec<_> = envelope
4395 .payload
4396 .actions
4397 .into_iter()
4398 .map(|action| MessageActionItem {
4399 title: action,
4400 properties: Default::default(),
4401 })
4402 .collect();
4403 this.update(&mut cx, |_, cx| {
4404 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4405 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4406 message: envelope.payload.message,
4407 actions: actions.clone(),
4408 lsp_name: envelope.payload.lsp_name,
4409 response_channel: tx,
4410 }));
4411
4412 anyhow::Ok(())
4413 })??;
4414
4415 // We drop `this` to avoid holding a reference in this future for too
4416 // long.
4417 // If we keep the reference, we might not drop the `Project` early
4418 // enough when closing a window and it will only get releases on the
4419 // next `flush_effects()` call.
4420 drop(this);
4421
4422 let mut rx = pin!(rx);
4423 let answer = rx.next().await;
4424
4425 Ok(LanguageServerPromptResponse {
4426 action_response: answer.and_then(|answer| {
4427 actions
4428 .iter()
4429 .position(|action| *action == answer)
4430 .map(|index| index as u64)
4431 }),
4432 })
4433 }
4434
4435 async fn handle_hide_toast(
4436 this: Entity<Self>,
4437 envelope: TypedEnvelope<proto::HideToast>,
4438 mut cx: AsyncApp,
4439 ) -> Result<()> {
4440 this.update(&mut cx, |_, cx| {
4441 cx.emit(Event::HideToast {
4442 notification_id: envelope.payload.notification_id.into(),
4443 });
4444 Ok(())
4445 })?
4446 }
4447
4448 // Collab sends UpdateWorktree protos as messages
4449 async fn handle_update_worktree(
4450 this: Entity<Self>,
4451 envelope: TypedEnvelope<proto::UpdateWorktree>,
4452 mut cx: AsyncApp,
4453 ) -> Result<()> {
4454 this.update(&mut cx, |this, cx| {
4455 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4456 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4457 worktree.update(cx, |worktree, _| {
4458 let worktree = worktree.as_remote_mut().unwrap();
4459 worktree.update_from_remote(envelope.payload);
4460 });
4461 }
4462 Ok(())
4463 })?
4464 }
4465
4466 async fn handle_update_buffer_from_ssh(
4467 this: Entity<Self>,
4468 envelope: TypedEnvelope<proto::UpdateBuffer>,
4469 cx: AsyncApp,
4470 ) -> Result<proto::Ack> {
4471 let buffer_store = this.read_with(&cx, |this, cx| {
4472 if let Some(remote_id) = this.remote_id() {
4473 let mut payload = envelope.payload.clone();
4474 payload.project_id = remote_id;
4475 cx.background_spawn(this.client.request(payload))
4476 .detach_and_log_err(cx);
4477 }
4478 this.buffer_store.clone()
4479 })?;
4480 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4481 }
4482
4483 async fn handle_update_buffer(
4484 this: Entity<Self>,
4485 envelope: TypedEnvelope<proto::UpdateBuffer>,
4486 cx: AsyncApp,
4487 ) -> Result<proto::Ack> {
4488 let buffer_store = this.read_with(&cx, |this, cx| {
4489 if let Some(ssh) = &this.ssh_client {
4490 let mut payload = envelope.payload.clone();
4491 payload.project_id = SSH_PROJECT_ID;
4492 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4493 .detach_and_log_err(cx);
4494 }
4495 this.buffer_store.clone()
4496 })?;
4497 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4498 }
4499
4500 fn retain_remotely_created_models(
4501 &mut self,
4502 cx: &mut Context<Self>,
4503 ) -> RemotelyCreatedModelGuard {
4504 {
4505 let mut remotely_create_models = self.remotely_created_models.lock();
4506 if remotely_create_models.retain_count == 0 {
4507 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4508 remotely_create_models.worktrees =
4509 self.worktree_store.read(cx).worktrees().collect();
4510 }
4511 remotely_create_models.retain_count += 1;
4512 }
4513 RemotelyCreatedModelGuard {
4514 remote_models: Arc::downgrade(&self.remotely_created_models),
4515 }
4516 }
4517
4518 async fn handle_create_buffer_for_peer(
4519 this: Entity<Self>,
4520 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4521 mut cx: AsyncApp,
4522 ) -> Result<()> {
4523 this.update(&mut cx, |this, cx| {
4524 this.buffer_store.update(cx, |buffer_store, cx| {
4525 buffer_store.handle_create_buffer_for_peer(
4526 envelope,
4527 this.replica_id(),
4528 this.capability(),
4529 cx,
4530 )
4531 })
4532 })?
4533 }
4534
4535 async fn handle_synchronize_buffers(
4536 this: Entity<Self>,
4537 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4538 mut cx: AsyncApp,
4539 ) -> Result<proto::SynchronizeBuffersResponse> {
4540 let response = this.update(&mut cx, |this, cx| {
4541 let client = this.client.clone();
4542 this.buffer_store.update(cx, |this, cx| {
4543 this.handle_synchronize_buffers(envelope, cx, client)
4544 })
4545 })??;
4546
4547 Ok(response)
4548 }
4549
4550 async fn handle_search_candidate_buffers(
4551 this: Entity<Self>,
4552 envelope: TypedEnvelope<proto::FindSearchCandidates>,
4553 mut cx: AsyncApp,
4554 ) -> Result<proto::FindSearchCandidatesResponse> {
4555 let peer_id = envelope.original_sender_id()?;
4556 let message = envelope.payload;
4557 let query = SearchQuery::from_proto(message.query.context("missing query field")?)?;
4558 let results = this.update(&mut cx, |this, cx| {
4559 this.find_search_candidate_buffers(&query, message.limit as _, cx)
4560 })?;
4561
4562 let mut response = proto::FindSearchCandidatesResponse {
4563 buffer_ids: Vec::new(),
4564 };
4565
4566 while let Ok(buffer) = results.recv().await {
4567 this.update(&mut cx, |this, cx| {
4568 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4569 response.buffer_ids.push(buffer_id.to_proto());
4570 })?;
4571 }
4572
4573 Ok(response)
4574 }
4575
4576 async fn handle_open_buffer_by_id(
4577 this: Entity<Self>,
4578 envelope: TypedEnvelope<proto::OpenBufferById>,
4579 mut cx: AsyncApp,
4580 ) -> Result<proto::OpenBufferResponse> {
4581 let peer_id = envelope.original_sender_id()?;
4582 let buffer_id = BufferId::new(envelope.payload.id)?;
4583 let buffer = this
4584 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4585 .await?;
4586 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4587 }
4588
4589 async fn handle_open_buffer_by_path(
4590 this: Entity<Self>,
4591 envelope: TypedEnvelope<proto::OpenBufferByPath>,
4592 mut cx: AsyncApp,
4593 ) -> Result<proto::OpenBufferResponse> {
4594 let peer_id = envelope.original_sender_id()?;
4595 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4596 let open_buffer = this.update(&mut cx, |this, cx| {
4597 this.open_buffer(
4598 ProjectPath {
4599 worktree_id,
4600 path: Arc::<Path>::from_proto(envelope.payload.path),
4601 },
4602 cx,
4603 )
4604 })?;
4605
4606 let buffer = open_buffer.await?;
4607 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4608 }
4609
4610 async fn handle_open_new_buffer(
4611 this: Entity<Self>,
4612 envelope: TypedEnvelope<proto::OpenNewBuffer>,
4613 mut cx: AsyncApp,
4614 ) -> Result<proto::OpenBufferResponse> {
4615 let buffer = this
4616 .update(&mut cx, |this, cx| this.create_buffer(cx))?
4617 .await?;
4618 let peer_id = envelope.original_sender_id()?;
4619
4620 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4621 }
4622
4623 fn respond_to_open_buffer_request(
4624 this: Entity<Self>,
4625 buffer: Entity<Buffer>,
4626 peer_id: proto::PeerId,
4627 cx: &mut AsyncApp,
4628 ) -> Result<proto::OpenBufferResponse> {
4629 this.update(cx, |this, cx| {
4630 let is_private = buffer
4631 .read(cx)
4632 .file()
4633 .map(|f| f.is_private())
4634 .unwrap_or_default();
4635 anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
4636 Ok(proto::OpenBufferResponse {
4637 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4638 })
4639 })?
4640 }
4641
4642 fn create_buffer_for_peer(
4643 &mut self,
4644 buffer: &Entity<Buffer>,
4645 peer_id: proto::PeerId,
4646 cx: &mut App,
4647 ) -> BufferId {
4648 self.buffer_store
4649 .update(cx, |buffer_store, cx| {
4650 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4651 })
4652 .detach_and_log_err(cx);
4653 buffer.read(cx).remote_id()
4654 }
4655
4656 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4657 let project_id = match self.client_state {
4658 ProjectClientState::Remote {
4659 sharing_has_stopped,
4660 remote_id,
4661 ..
4662 } => {
4663 if sharing_has_stopped {
4664 return Task::ready(Err(anyhow!(
4665 "can't synchronize remote buffers on a readonly project"
4666 )));
4667 } else {
4668 remote_id
4669 }
4670 }
4671 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4672 return Task::ready(Err(anyhow!(
4673 "can't synchronize remote buffers on a local project"
4674 )));
4675 }
4676 };
4677
4678 let client = self.client.clone();
4679 cx.spawn(async move |this, cx| {
4680 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
4681 this.buffer_store.read(cx).buffer_version_info(cx)
4682 })?;
4683 let response = client
4684 .request(proto::SynchronizeBuffers {
4685 project_id,
4686 buffers,
4687 })
4688 .await?;
4689
4690 let send_updates_for_buffers = this.update(cx, |this, cx| {
4691 response
4692 .buffers
4693 .into_iter()
4694 .map(|buffer| {
4695 let client = client.clone();
4696 let buffer_id = match BufferId::new(buffer.id) {
4697 Ok(id) => id,
4698 Err(e) => {
4699 return Task::ready(Err(e));
4700 }
4701 };
4702 let remote_version = language::proto::deserialize_version(&buffer.version);
4703 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4704 let operations =
4705 buffer.read(cx).serialize_ops(Some(remote_version), cx);
4706 cx.background_spawn(async move {
4707 let operations = operations.await;
4708 for chunk in split_operations(operations) {
4709 client
4710 .request(proto::UpdateBuffer {
4711 project_id,
4712 buffer_id: buffer_id.into(),
4713 operations: chunk,
4714 })
4715 .await?;
4716 }
4717 anyhow::Ok(())
4718 })
4719 } else {
4720 Task::ready(Ok(()))
4721 }
4722 })
4723 .collect::<Vec<_>>()
4724 })?;
4725
4726 // Any incomplete buffers have open requests waiting. Request that the host sends
4727 // creates these buffers for us again to unblock any waiting futures.
4728 for id in incomplete_buffer_ids {
4729 cx.background_spawn(client.request(proto::OpenBufferById {
4730 project_id,
4731 id: id.into(),
4732 }))
4733 .detach();
4734 }
4735
4736 futures::future::join_all(send_updates_for_buffers)
4737 .await
4738 .into_iter()
4739 .collect()
4740 })
4741 }
4742
4743 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4744 self.worktree_store.read(cx).worktree_metadata_protos(cx)
4745 }
4746
4747 /// Iterator of all open buffers that have unsaved changes
4748 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4749 self.buffer_store.read(cx).buffers().filter_map(|buf| {
4750 let buf = buf.read(cx);
4751 if buf.is_dirty() {
4752 buf.project_path(cx)
4753 } else {
4754 None
4755 }
4756 })
4757 }
4758
4759 fn set_worktrees_from_proto(
4760 &mut self,
4761 worktrees: Vec<proto::WorktreeMetadata>,
4762 cx: &mut Context<Project>,
4763 ) -> Result<()> {
4764 self.worktree_store.update(cx, |worktree_store, cx| {
4765 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4766 })
4767 }
4768
4769 fn set_collaborators_from_proto(
4770 &mut self,
4771 messages: Vec<proto::Collaborator>,
4772 cx: &mut Context<Self>,
4773 ) -> Result<()> {
4774 let mut collaborators = HashMap::default();
4775 for message in messages {
4776 let collaborator = Collaborator::from_proto(message)?;
4777 collaborators.insert(collaborator.peer_id, collaborator);
4778 }
4779 for old_peer_id in self.collaborators.keys() {
4780 if !collaborators.contains_key(old_peer_id) {
4781 cx.emit(Event::CollaboratorLeft(*old_peer_id));
4782 }
4783 }
4784 self.collaborators = collaborators;
4785 Ok(())
4786 }
4787
4788 pub fn supplementary_language_servers<'a>(
4789 &'a self,
4790 cx: &'a App,
4791 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4792 self.lsp_store.read(cx).supplementary_language_servers()
4793 }
4794
4795 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4796 self.lsp_store.update(cx, |this, cx| {
4797 this.language_servers_for_local_buffer(buffer, cx)
4798 .any(
4799 |(_, server)| match server.capabilities().inlay_hint_provider {
4800 Some(lsp::OneOf::Left(enabled)) => enabled,
4801 Some(lsp::OneOf::Right(_)) => true,
4802 None => false,
4803 },
4804 )
4805 })
4806 }
4807
4808 pub fn language_server_id_for_name(
4809 &self,
4810 buffer: &Buffer,
4811 name: &str,
4812 cx: &mut App,
4813 ) -> Task<Option<LanguageServerId>> {
4814 if self.is_local() {
4815 Task::ready(self.lsp_store.update(cx, |lsp_store, cx| {
4816 lsp_store
4817 .language_servers_for_local_buffer(buffer, cx)
4818 .find_map(|(adapter, server)| {
4819 if adapter.name.0 == name {
4820 Some(server.server_id())
4821 } else {
4822 None
4823 }
4824 })
4825 }))
4826 } else if let Some(project_id) = self.remote_id() {
4827 let request = self.client.request(proto::LanguageServerIdForName {
4828 project_id,
4829 buffer_id: buffer.remote_id().to_proto(),
4830 name: name.to_string(),
4831 });
4832 cx.background_spawn(async move {
4833 let response = request.await.log_err()?;
4834 response.server_id.map(LanguageServerId::from_proto)
4835 })
4836 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
4837 let request =
4838 ssh_client
4839 .read(cx)
4840 .proto_client()
4841 .request(proto::LanguageServerIdForName {
4842 project_id: SSH_PROJECT_ID,
4843 buffer_id: buffer.remote_id().to_proto(),
4844 name: name.to_string(),
4845 });
4846 cx.background_spawn(async move {
4847 let response = request.await.log_err()?;
4848 response.server_id.map(LanguageServerId::from_proto)
4849 })
4850 } else {
4851 Task::ready(None)
4852 }
4853 }
4854
4855 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
4856 self.lsp_store.update(cx, |this, cx| {
4857 this.language_servers_for_local_buffer(buffer, cx)
4858 .next()
4859 .is_some()
4860 })
4861 }
4862
4863 pub fn git_init(
4864 &self,
4865 path: Arc<Path>,
4866 fallback_branch_name: String,
4867 cx: &App,
4868 ) -> Task<Result<()>> {
4869 self.git_store
4870 .read(cx)
4871 .git_init(path, fallback_branch_name, cx)
4872 }
4873
4874 pub fn buffer_store(&self) -> &Entity<BufferStore> {
4875 &self.buffer_store
4876 }
4877
4878 pub fn git_store(&self) -> &Entity<GitStore> {
4879 &self.git_store
4880 }
4881
4882 #[cfg(test)]
4883 fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
4884 cx.spawn(async move |this, cx| {
4885 let scans_complete = this
4886 .read_with(cx, |this, cx| {
4887 this.worktrees(cx)
4888 .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
4889 .collect::<Vec<_>>()
4890 })
4891 .unwrap();
4892 join_all(scans_complete).await;
4893 let barriers = this
4894 .update(cx, |this, cx| {
4895 let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
4896 repos
4897 .into_iter()
4898 .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
4899 .collect::<Vec<_>>()
4900 })
4901 .unwrap();
4902 join_all(barriers).await;
4903 })
4904 }
4905
4906 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
4907 self.git_store.read(cx).active_repository()
4908 }
4909
4910 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
4911 self.git_store.read(cx).repositories()
4912 }
4913
4914 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
4915 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
4916 }
4917
4918 pub fn set_agent_location(
4919 &mut self,
4920 new_location: Option<AgentLocation>,
4921 cx: &mut Context<Self>,
4922 ) {
4923 if let Some(old_location) = self.agent_location.as_ref() {
4924 old_location
4925 .buffer
4926 .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
4927 .ok();
4928 }
4929
4930 if let Some(location) = new_location.as_ref() {
4931 location
4932 .buffer
4933 .update(cx, |buffer, cx| {
4934 buffer.set_agent_selections(
4935 Arc::from([language::Selection {
4936 id: 0,
4937 start: location.position,
4938 end: location.position,
4939 reversed: false,
4940 goal: language::SelectionGoal::None,
4941 }]),
4942 false,
4943 CursorShape::Hollow,
4944 cx,
4945 )
4946 })
4947 .ok();
4948 }
4949
4950 self.agent_location = new_location;
4951 cx.emit(Event::AgentLocationChanged);
4952 }
4953
4954 pub fn agent_location(&self) -> Option<AgentLocation> {
4955 self.agent_location.clone()
4956 }
4957}
4958
4959pub struct PathMatchCandidateSet {
4960 pub snapshot: Snapshot,
4961 pub include_ignored: bool,
4962 pub include_root_name: bool,
4963 pub candidates: Candidates,
4964}
4965
4966pub enum Candidates {
4967 /// Only consider directories.
4968 Directories,
4969 /// Only consider files.
4970 Files,
4971 /// Consider directories and files.
4972 Entries,
4973}
4974
4975impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4976 type Candidates = PathMatchCandidateSetIter<'a>;
4977
4978 fn id(&self) -> usize {
4979 self.snapshot.id().to_usize()
4980 }
4981
4982 fn len(&self) -> usize {
4983 match self.candidates {
4984 Candidates::Files => {
4985 if self.include_ignored {
4986 self.snapshot.file_count()
4987 } else {
4988 self.snapshot.visible_file_count()
4989 }
4990 }
4991
4992 Candidates::Directories => {
4993 if self.include_ignored {
4994 self.snapshot.dir_count()
4995 } else {
4996 self.snapshot.visible_dir_count()
4997 }
4998 }
4999
5000 Candidates::Entries => {
5001 if self.include_ignored {
5002 self.snapshot.entry_count()
5003 } else {
5004 self.snapshot.visible_entry_count()
5005 }
5006 }
5007 }
5008 }
5009
5010 fn prefix(&self) -> Arc<str> {
5011 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5012 self.snapshot.root_name().into()
5013 } else if self.include_root_name {
5014 format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
5015 } else {
5016 Arc::default()
5017 }
5018 }
5019
5020 fn candidates(&'a self, start: usize) -> Self::Candidates {
5021 PathMatchCandidateSetIter {
5022 traversal: match self.candidates {
5023 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5024 Candidates::Files => self.snapshot.files(self.include_ignored, start),
5025 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5026 },
5027 }
5028 }
5029}
5030
5031pub struct PathMatchCandidateSetIter<'a> {
5032 traversal: Traversal<'a>,
5033}
5034
5035impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5036 type Item = fuzzy::PathMatchCandidate<'a>;
5037
5038 fn next(&mut self) -> Option<Self::Item> {
5039 self.traversal
5040 .next()
5041 .map(|entry| fuzzy::PathMatchCandidate {
5042 is_dir: entry.kind.is_dir(),
5043 path: &entry.path,
5044 char_bag: entry.char_bag,
5045 })
5046 }
5047}
5048
5049impl EventEmitter<Event> for Project {}
5050
5051impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5052 fn from(val: &'a ProjectPath) -> Self {
5053 SettingsLocation {
5054 worktree_id: val.worktree_id,
5055 path: val.path.as_ref(),
5056 }
5057 }
5058}
5059
5060impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5061 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5062 Self {
5063 worktree_id,
5064 path: path.as_ref().into(),
5065 }
5066 }
5067}
5068
5069pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5070 let mut path_components = path.components();
5071 let mut base_components = base.components();
5072 let mut components: Vec<Component> = Vec::new();
5073 loop {
5074 match (path_components.next(), base_components.next()) {
5075 (None, None) => break,
5076 (Some(a), None) => {
5077 components.push(a);
5078 components.extend(path_components.by_ref());
5079 break;
5080 }
5081 (None, _) => components.push(Component::ParentDir),
5082 (Some(a), Some(b)) if components.is_empty() && a == b => (),
5083 (Some(a), Some(Component::CurDir)) => components.push(a),
5084 (Some(a), Some(_)) => {
5085 components.push(Component::ParentDir);
5086 for _ in base_components {
5087 components.push(Component::ParentDir);
5088 }
5089 components.push(a);
5090 components.extend(path_components.by_ref());
5091 break;
5092 }
5093 }
5094 }
5095 components.iter().map(|c| c.as_os_str()).collect()
5096}
5097
5098fn resolve_path(base: &Path, path: &Path) -> PathBuf {
5099 let mut result = base.to_path_buf();
5100 for component in path.components() {
5101 match component {
5102 Component::ParentDir => {
5103 result.pop();
5104 }
5105 Component::CurDir => (),
5106 _ => result.push(component),
5107 }
5108 }
5109 result
5110}
5111
5112/// ResolvedPath is a path that has been resolved to either a ProjectPath
5113/// or an AbsPath and that *exists*.
5114#[derive(Debug, Clone)]
5115pub enum ResolvedPath {
5116 ProjectPath {
5117 project_path: ProjectPath,
5118 is_dir: bool,
5119 },
5120 AbsPath {
5121 path: PathBuf,
5122 is_dir: bool,
5123 },
5124}
5125
5126impl ResolvedPath {
5127 pub fn abs_path(&self) -> Option<&Path> {
5128 match self {
5129 Self::AbsPath { path, .. } => Some(path.as_path()),
5130 _ => None,
5131 }
5132 }
5133
5134 pub fn into_abs_path(self) -> Option<PathBuf> {
5135 match self {
5136 Self::AbsPath { path, .. } => Some(path),
5137 _ => None,
5138 }
5139 }
5140
5141 pub fn project_path(&self) -> Option<&ProjectPath> {
5142 match self {
5143 Self::ProjectPath { project_path, .. } => Some(&project_path),
5144 _ => None,
5145 }
5146 }
5147
5148 pub fn is_file(&self) -> bool {
5149 !self.is_dir()
5150 }
5151
5152 pub fn is_dir(&self) -> bool {
5153 match self {
5154 Self::ProjectPath { is_dir, .. } => *is_dir,
5155 Self::AbsPath { is_dir, .. } => *is_dir,
5156 }
5157 }
5158}
5159
5160impl ProjectItem for Buffer {
5161 fn try_open(
5162 project: &Entity<Project>,
5163 path: &ProjectPath,
5164 cx: &mut App,
5165 ) -> Option<Task<Result<Entity<Self>>>> {
5166 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5167 }
5168
5169 fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
5170 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5171 }
5172
5173 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5174 self.file().map(|file| ProjectPath {
5175 worktree_id: file.worktree_id(cx),
5176 path: file.path().clone(),
5177 })
5178 }
5179
5180 fn is_dirty(&self) -> bool {
5181 self.is_dirty()
5182 }
5183}
5184
5185impl Completion {
5186 pub fn kind(&self) -> Option<CompletionItemKind> {
5187 self.source
5188 // `lsp::CompletionListItemDefaults` has no `kind` field
5189 .lsp_completion(false)
5190 .and_then(|lsp_completion| lsp_completion.kind)
5191 }
5192
5193 pub fn label(&self) -> Option<String> {
5194 self.source
5195 .lsp_completion(false)
5196 .map(|lsp_completion| lsp_completion.label.clone())
5197 }
5198
5199 /// A key that can be used to sort completions when displaying
5200 /// them to the user.
5201 pub fn sort_key(&self) -> (usize, &str) {
5202 const DEFAULT_KIND_KEY: usize = 3;
5203 let kind_key = self
5204 .kind()
5205 .and_then(|lsp_completion_kind| match lsp_completion_kind {
5206 lsp::CompletionItemKind::KEYWORD => Some(0),
5207 lsp::CompletionItemKind::VARIABLE => Some(1),
5208 lsp::CompletionItemKind::CONSTANT => Some(2),
5209 _ => None,
5210 })
5211 .unwrap_or(DEFAULT_KIND_KEY);
5212 (kind_key, &self.label.text[self.label.filter_range.clone()])
5213 }
5214
5215 /// Whether this completion is a snippet.
5216 pub fn is_snippet(&self) -> bool {
5217 self.source
5218 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5219 .lsp_completion(true)
5220 .map_or(false, |lsp_completion| {
5221 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5222 })
5223 }
5224
5225 /// Returns the corresponding color for this completion.
5226 ///
5227 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5228 pub fn color(&self) -> Option<Hsla> {
5229 // `lsp::CompletionListItemDefaults` has no `kind` field
5230 let lsp_completion = self.source.lsp_completion(false)?;
5231 if lsp_completion.kind? == CompletionItemKind::COLOR {
5232 return color_extractor::extract_color(&lsp_completion);
5233 }
5234 None
5235 }
5236}
5237
5238pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
5239 entries.sort_by(|entry_a, entry_b| {
5240 let entry_a = entry_a.as_ref();
5241 let entry_b = entry_b.as_ref();
5242 compare_paths(
5243 (&entry_a.path, entry_a.is_file()),
5244 (&entry_b.path, entry_b.is_file()),
5245 )
5246 });
5247}
5248
5249fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5250 match level {
5251 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5252 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5253 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5254 }
5255}