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