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