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