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