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