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