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(
1334 REMOTE_SERVER_PROJECT_ID,
1335 worktree_store.clone(),
1336 remote.read(cx).proto_client(),
1337 cx,
1338 )
1339 });
1340 let task_store = cx.new(|cx| {
1341 TaskStore::remote(
1342 buffer_store.downgrade(),
1343 worktree_store.clone(),
1344 toolchain_store.read(cx).as_language_toolchain_store(),
1345 remote.read(cx).proto_client(),
1346 REMOTE_SERVER_PROJECT_ID,
1347 cx,
1348 )
1349 });
1350
1351 let settings_observer = cx.new(|cx| {
1352 SettingsObserver::new_remote(
1353 fs.clone(),
1354 worktree_store.clone(),
1355 task_store.clone(),
1356 Some(remote_proto.clone()),
1357 cx,
1358 )
1359 });
1360 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1361 .detach();
1362
1363 let environment = cx.new(|cx| {
1364 ProjectEnvironment::new(
1365 None,
1366 worktree_store.downgrade(),
1367 Some(remote.downgrade()),
1368 false,
1369 cx,
1370 )
1371 });
1372
1373 let lsp_store = cx.new(|cx| {
1374 LspStore::new_remote(
1375 buffer_store.clone(),
1376 worktree_store.clone(),
1377 languages.clone(),
1378 remote_proto.clone(),
1379 REMOTE_SERVER_PROJECT_ID,
1380 cx,
1381 )
1382 });
1383 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1384
1385 let breakpoint_store = cx.new(|_| {
1386 BreakpointStore::remote(
1387 REMOTE_SERVER_PROJECT_ID,
1388 remote_proto.clone(),
1389 buffer_store.clone(),
1390 worktree_store.clone(),
1391 )
1392 });
1393
1394 let dap_store = cx.new(|cx| {
1395 DapStore::new_remote(
1396 REMOTE_SERVER_PROJECT_ID,
1397 remote.clone(),
1398 breakpoint_store.clone(),
1399 worktree_store.clone(),
1400 node.clone(),
1401 client.http_client(),
1402 fs.clone(),
1403 cx,
1404 )
1405 });
1406
1407 let git_store = cx.new(|cx| {
1408 GitStore::remote(
1409 &worktree_store,
1410 buffer_store.clone(),
1411 remote_proto.clone(),
1412 REMOTE_SERVER_PROJECT_ID,
1413 cx,
1414 )
1415 });
1416
1417 let agent_server_store =
1418 cx.new(|_| AgentServerStore::remote(REMOTE_SERVER_PROJECT_ID, remote.clone()));
1419
1420 cx.subscribe(&remote, Self::on_remote_client_event).detach();
1421
1422 let this = Self {
1423 buffer_ordered_messages_tx: tx,
1424 collaborators: Default::default(),
1425 worktree_store,
1426 buffer_store,
1427 image_store,
1428 lsp_store,
1429 context_server_store,
1430 breakpoint_store,
1431 dap_store,
1432 join_project_response_message_id: 0,
1433 client_state: ProjectClientState::Local,
1434 git_store,
1435 agent_server_store,
1436 client_subscriptions: Vec::new(),
1437 _subscriptions: vec![
1438 cx.on_release(Self::release),
1439 cx.on_app_quit(|this, cx| {
1440 let shutdown = this.remote_client.take().and_then(|client| {
1441 client.update(cx, |client, cx| {
1442 client.shutdown_processes(
1443 Some(proto::ShutdownRemoteServer {}),
1444 cx.background_executor().clone(),
1445 )
1446 })
1447 });
1448
1449 cx.background_executor().spawn(async move {
1450 if let Some(shutdown) = shutdown {
1451 shutdown.await;
1452 }
1453 })
1454 }),
1455 ],
1456 active_entry: None,
1457 snippets,
1458 languages,
1459 collab_client: client,
1460 task_store,
1461 user_store,
1462 settings_observer,
1463 fs,
1464 remote_client: Some(remote.clone()),
1465 buffers_needing_diff: Default::default(),
1466 git_diff_debouncer: DebouncedDelay::new(),
1467 terminals: Terminals {
1468 local_handles: Vec::new(),
1469 },
1470 node: Some(node),
1471 search_history: Self::new_search_history(),
1472 environment,
1473 remotely_created_models: Default::default(),
1474
1475 search_included_history: Self::new_search_history(),
1476 search_excluded_history: Self::new_search_history(),
1477
1478 toolchain_store: Some(toolchain_store),
1479 agent_location: None,
1480 };
1481
1482 // remote server -> local machine handlers
1483 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &cx.entity());
1484 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.buffer_store);
1485 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.worktree_store);
1486 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.lsp_store);
1487 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.dap_store);
1488 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.breakpoint_store);
1489 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.settings_observer);
1490 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.git_store);
1491 remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.agent_server_store);
1492
1493 remote_proto.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1494 remote_proto.add_entity_message_handler(Self::handle_create_image_for_peer);
1495 remote_proto.add_entity_message_handler(Self::handle_update_worktree);
1496 remote_proto.add_entity_message_handler(Self::handle_update_project);
1497 remote_proto.add_entity_message_handler(Self::handle_toast);
1498 remote_proto.add_entity_request_handler(Self::handle_language_server_prompt_request);
1499 remote_proto.add_entity_message_handler(Self::handle_hide_toast);
1500 remote_proto.add_entity_request_handler(Self::handle_update_buffer_from_remote_server);
1501 remote_proto.add_entity_request_handler(Self::handle_trust_worktrees);
1502 remote_proto.add_entity_request_handler(Self::handle_restrict_worktrees);
1503
1504 BufferStore::init(&remote_proto);
1505 LspStore::init(&remote_proto);
1506 SettingsObserver::init(&remote_proto);
1507 TaskStore::init(Some(&remote_proto));
1508 ToolchainStore::init(&remote_proto);
1509 DapStore::init(&remote_proto, cx);
1510 BreakpointStore::init(&remote_proto);
1511 GitStore::init(&remote_proto);
1512 AgentServerStore::init_remote(&remote_proto);
1513
1514 this
1515 })
1516 }
1517
1518 pub async fn in_room(
1519 remote_id: u64,
1520 client: Arc<Client>,
1521 user_store: Entity<UserStore>,
1522 languages: Arc<LanguageRegistry>,
1523 fs: Arc<dyn Fs>,
1524 cx: AsyncApp,
1525 ) -> Result<Entity<Self>> {
1526 client.connect(true, &cx).await.into_response()?;
1527
1528 let subscriptions = [
1529 EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
1530 EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
1531 EntitySubscription::GitStore(client.subscribe_to_entity::<GitStore>(remote_id)?),
1532 EntitySubscription::WorktreeStore(
1533 client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
1534 ),
1535 EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
1536 EntitySubscription::SettingsObserver(
1537 client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
1538 ),
1539 EntitySubscription::DapStore(client.subscribe_to_entity::<DapStore>(remote_id)?),
1540 ];
1541 let committer = get_git_committer(&cx).await;
1542 let response = client
1543 .request_envelope(proto::JoinProject {
1544 project_id: remote_id,
1545 committer_email: committer.email,
1546 committer_name: committer.name,
1547 })
1548 .await?;
1549 Self::from_join_project_response(
1550 response,
1551 subscriptions,
1552 client,
1553 false,
1554 user_store,
1555 languages,
1556 fs,
1557 cx,
1558 )
1559 .await
1560 }
1561
1562 async fn from_join_project_response(
1563 response: TypedEnvelope<proto::JoinProjectResponse>,
1564 subscriptions: [EntitySubscription; 7],
1565 client: Arc<Client>,
1566 run_tasks: bool,
1567 user_store: Entity<UserStore>,
1568 languages: Arc<LanguageRegistry>,
1569 fs: Arc<dyn Fs>,
1570 mut cx: AsyncApp,
1571 ) -> Result<Entity<Self>> {
1572 let remote_id = response.payload.project_id;
1573 let role = response.payload.role();
1574
1575 let path_style = if response.payload.windows_paths {
1576 PathStyle::Windows
1577 } else {
1578 PathStyle::Posix
1579 };
1580
1581 let worktree_store = cx.new(|_| {
1582 WorktreeStore::remote(
1583 true,
1584 client.clone().into(),
1585 response.payload.project_id,
1586 path_style,
1587 )
1588 })?;
1589 let buffer_store = cx.new(|cx| {
1590 BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1591 })?;
1592 let image_store = cx.new(|cx| {
1593 ImageStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1594 })?;
1595
1596 let environment =
1597 cx.new(|cx| ProjectEnvironment::new(None, worktree_store.downgrade(), None, true, cx))?;
1598 let breakpoint_store = cx.new(|_| {
1599 BreakpointStore::remote(
1600 remote_id,
1601 client.clone().into(),
1602 buffer_store.clone(),
1603 worktree_store.clone(),
1604 )
1605 })?;
1606 let dap_store = cx.new(|cx| {
1607 DapStore::new_collab(
1608 remote_id,
1609 client.clone().into(),
1610 breakpoint_store.clone(),
1611 worktree_store.clone(),
1612 fs.clone(),
1613 cx,
1614 )
1615 })?;
1616
1617 let lsp_store = cx.new(|cx| {
1618 LspStore::new_remote(
1619 buffer_store.clone(),
1620 worktree_store.clone(),
1621 languages.clone(),
1622 client.clone().into(),
1623 remote_id,
1624 cx,
1625 )
1626 })?;
1627
1628 let task_store = cx.new(|cx| {
1629 if run_tasks {
1630 TaskStore::remote(
1631 buffer_store.downgrade(),
1632 worktree_store.clone(),
1633 Arc::new(EmptyToolchainStore),
1634 client.clone().into(),
1635 remote_id,
1636 cx,
1637 )
1638 } else {
1639 TaskStore::Noop
1640 }
1641 })?;
1642
1643 let settings_observer = cx.new(|cx| {
1644 SettingsObserver::new_remote(
1645 fs.clone(),
1646 worktree_store.clone(),
1647 task_store.clone(),
1648 None,
1649 cx,
1650 )
1651 })?;
1652
1653 let git_store = cx.new(|cx| {
1654 GitStore::remote(
1655 // In this remote case we pass None for the environment
1656 &worktree_store,
1657 buffer_store.clone(),
1658 client.clone().into(),
1659 remote_id,
1660 cx,
1661 )
1662 })?;
1663
1664 let agent_server_store = cx.new(|cx| AgentServerStore::collab(cx))?;
1665 let replica_id = ReplicaId::new(response.payload.replica_id as u16);
1666
1667 let project = cx.new(|cx| {
1668 let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1669
1670 let weak_self = cx.weak_entity();
1671 let context_server_store =
1672 cx.new(|cx| ContextServerStore::new(worktree_store.clone(), weak_self, cx));
1673
1674 let mut worktrees = Vec::new();
1675 for worktree in response.payload.worktrees {
1676 let worktree = Worktree::remote(
1677 remote_id,
1678 replica_id,
1679 worktree,
1680 client.clone().into(),
1681 path_style,
1682 cx,
1683 );
1684 worktrees.push(worktree);
1685 }
1686
1687 let (tx, rx) = mpsc::unbounded();
1688 cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1689 .detach();
1690
1691 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1692 .detach();
1693
1694 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1695 .detach();
1696 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1697 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1698 .detach();
1699
1700 cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1701
1702 let mut project = Self {
1703 buffer_ordered_messages_tx: tx,
1704 buffer_store: buffer_store.clone(),
1705 image_store,
1706 worktree_store: worktree_store.clone(),
1707 lsp_store: lsp_store.clone(),
1708 context_server_store,
1709 active_entry: None,
1710 collaborators: Default::default(),
1711 join_project_response_message_id: response.message_id,
1712 languages,
1713 user_store: user_store.clone(),
1714 task_store,
1715 snippets,
1716 fs,
1717 remote_client: None,
1718 settings_observer: settings_observer.clone(),
1719 client_subscriptions: Default::default(),
1720 _subscriptions: vec![cx.on_release(Self::release)],
1721 collab_client: client.clone(),
1722 client_state: ProjectClientState::Remote {
1723 sharing_has_stopped: false,
1724 capability: Capability::ReadWrite,
1725 remote_id,
1726 replica_id,
1727 },
1728 breakpoint_store,
1729 dap_store: dap_store.clone(),
1730 git_store: git_store.clone(),
1731 agent_server_store,
1732 buffers_needing_diff: Default::default(),
1733 git_diff_debouncer: DebouncedDelay::new(),
1734 terminals: Terminals {
1735 local_handles: Vec::new(),
1736 },
1737 node: None,
1738 search_history: Self::new_search_history(),
1739 search_included_history: Self::new_search_history(),
1740 search_excluded_history: Self::new_search_history(),
1741 environment,
1742 remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1743 toolchain_store: None,
1744 agent_location: None,
1745 };
1746 project.set_role(role, cx);
1747 for worktree in worktrees {
1748 project.add_worktree(&worktree, cx);
1749 }
1750 project
1751 })?;
1752
1753 let weak_project = project.downgrade();
1754 lsp_store
1755 .update(&mut cx, |lsp_store, cx| {
1756 lsp_store.set_language_server_statuses_from_proto(
1757 weak_project,
1758 response.payload.language_servers,
1759 response.payload.language_server_capabilities,
1760 cx,
1761 );
1762 })
1763 .ok();
1764
1765 let subscriptions = subscriptions
1766 .into_iter()
1767 .map(|s| match s {
1768 EntitySubscription::BufferStore(subscription) => {
1769 subscription.set_entity(&buffer_store, &cx)
1770 }
1771 EntitySubscription::WorktreeStore(subscription) => {
1772 subscription.set_entity(&worktree_store, &cx)
1773 }
1774 EntitySubscription::GitStore(subscription) => {
1775 subscription.set_entity(&git_store, &cx)
1776 }
1777 EntitySubscription::SettingsObserver(subscription) => {
1778 subscription.set_entity(&settings_observer, &cx)
1779 }
1780 EntitySubscription::Project(subscription) => subscription.set_entity(&project, &cx),
1781 EntitySubscription::LspStore(subscription) => {
1782 subscription.set_entity(&lsp_store, &cx)
1783 }
1784 EntitySubscription::DapStore(subscription) => {
1785 subscription.set_entity(&dap_store, &cx)
1786 }
1787 })
1788 .collect::<Vec<_>>();
1789
1790 let user_ids = response
1791 .payload
1792 .collaborators
1793 .iter()
1794 .map(|peer| peer.user_id)
1795 .collect();
1796 user_store
1797 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
1798 .await?;
1799
1800 project.update(&mut cx, |this, cx| {
1801 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1802 this.client_subscriptions.extend(subscriptions);
1803 anyhow::Ok(())
1804 })??;
1805
1806 Ok(project)
1807 }
1808
1809 fn new_search_history() -> SearchHistory {
1810 SearchHistory::new(
1811 Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1812 search_history::QueryInsertionBehavior::AlwaysInsert,
1813 )
1814 }
1815
1816 fn release(&mut self, cx: &mut App) {
1817 if let Some(client) = self.remote_client.take() {
1818 let shutdown = client.update(cx, |client, cx| {
1819 client.shutdown_processes(
1820 Some(proto::ShutdownRemoteServer {}),
1821 cx.background_executor().clone(),
1822 )
1823 });
1824
1825 cx.background_spawn(async move {
1826 if let Some(shutdown) = shutdown {
1827 shutdown.await;
1828 }
1829 })
1830 .detach()
1831 }
1832
1833 match &self.client_state {
1834 ProjectClientState::Local => {}
1835 ProjectClientState::Shared { .. } => {
1836 let _ = self.unshare_internal(cx);
1837 }
1838 ProjectClientState::Remote { remote_id, .. } => {
1839 let _ = self.collab_client.send(proto::LeaveProject {
1840 project_id: *remote_id,
1841 });
1842 self.disconnected_from_host_internal(cx);
1843 }
1844 }
1845 }
1846
1847 #[cfg(any(test, feature = "test-support"))]
1848 pub async fn example(
1849 root_paths: impl IntoIterator<Item = &Path>,
1850 cx: &mut AsyncApp,
1851 ) -> Entity<Project> {
1852 use clock::FakeSystemClock;
1853
1854 let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
1855 let languages = LanguageRegistry::test(cx.background_executor().clone());
1856 let clock = Arc::new(FakeSystemClock::new());
1857 let http_client = http_client::FakeHttpClient::with_404_response();
1858 let client = cx
1859 .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1860 .unwrap();
1861 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx)).unwrap();
1862 let project = cx
1863 .update(|cx| {
1864 Project::local(
1865 client,
1866 node_runtime::NodeRuntime::unavailable(),
1867 user_store,
1868 Arc::new(languages),
1869 fs,
1870 None,
1871 false,
1872 cx,
1873 )
1874 })
1875 .unwrap();
1876 for path in root_paths {
1877 let (tree, _) = project
1878 .update(cx, |project, cx| {
1879 project.find_or_create_worktree(path, true, cx)
1880 })
1881 .unwrap()
1882 .await
1883 .unwrap();
1884 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1885 .unwrap()
1886 .await;
1887 }
1888 project
1889 }
1890
1891 #[cfg(any(test, feature = "test-support"))]
1892 pub async fn test(
1893 fs: Arc<dyn Fs>,
1894 root_paths: impl IntoIterator<Item = &Path>,
1895 cx: &mut gpui::TestAppContext,
1896 ) -> Entity<Project> {
1897 Self::test_project(fs, root_paths, false, cx).await
1898 }
1899
1900 #[cfg(any(test, feature = "test-support"))]
1901 pub async fn test_with_worktree_trust(
1902 fs: Arc<dyn Fs>,
1903 root_paths: impl IntoIterator<Item = &Path>,
1904 cx: &mut gpui::TestAppContext,
1905 ) -> Entity<Project> {
1906 Self::test_project(fs, root_paths, true, cx).await
1907 }
1908
1909 #[cfg(any(test, feature = "test-support"))]
1910 async fn test_project(
1911 fs: Arc<dyn Fs>,
1912 root_paths: impl IntoIterator<Item = &Path>,
1913 init_worktree_trust: bool,
1914 cx: &mut gpui::TestAppContext,
1915 ) -> Entity<Project> {
1916 use clock::FakeSystemClock;
1917
1918 let languages = LanguageRegistry::test(cx.executor());
1919 let clock = Arc::new(FakeSystemClock::new());
1920 let http_client = http_client::FakeHttpClient::with_404_response();
1921 let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1922 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1923 let project = cx.update(|cx| {
1924 Project::local(
1925 client,
1926 node_runtime::NodeRuntime::unavailable(),
1927 user_store,
1928 Arc::new(languages),
1929 fs,
1930 None,
1931 init_worktree_trust,
1932 cx,
1933 )
1934 });
1935 for path in root_paths {
1936 let (tree, _) = project
1937 .update(cx, |project, cx| {
1938 project.find_or_create_worktree(path, true, cx)
1939 })
1940 .await
1941 .unwrap();
1942
1943 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1944 .await;
1945 }
1946 project
1947 }
1948
1949 #[inline]
1950 pub fn dap_store(&self) -> Entity<DapStore> {
1951 self.dap_store.clone()
1952 }
1953
1954 #[inline]
1955 pub fn breakpoint_store(&self) -> Entity<BreakpointStore> {
1956 self.breakpoint_store.clone()
1957 }
1958
1959 pub fn active_debug_session(&self, cx: &App) -> Option<(Entity<Session>, ActiveStackFrame)> {
1960 let active_position = self.breakpoint_store.read(cx).active_position()?;
1961 let session = self
1962 .dap_store
1963 .read(cx)
1964 .session_by_id(active_position.session_id)?;
1965 Some((session, active_position.clone()))
1966 }
1967
1968 #[inline]
1969 pub fn lsp_store(&self) -> Entity<LspStore> {
1970 self.lsp_store.clone()
1971 }
1972
1973 #[inline]
1974 pub fn worktree_store(&self) -> Entity<WorktreeStore> {
1975 self.worktree_store.clone()
1976 }
1977
1978 #[inline]
1979 pub fn context_server_store(&self) -> Entity<ContextServerStore> {
1980 self.context_server_store.clone()
1981 }
1982
1983 #[inline]
1984 pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
1985 self.buffer_store.read(cx).get(remote_id)
1986 }
1987
1988 #[inline]
1989 pub fn languages(&self) -> &Arc<LanguageRegistry> {
1990 &self.languages
1991 }
1992
1993 #[inline]
1994 pub fn client(&self) -> Arc<Client> {
1995 self.collab_client.clone()
1996 }
1997
1998 #[inline]
1999 pub fn remote_client(&self) -> Option<Entity<RemoteClient>> {
2000 self.remote_client.clone()
2001 }
2002
2003 #[inline]
2004 pub fn user_store(&self) -> Entity<UserStore> {
2005 self.user_store.clone()
2006 }
2007
2008 #[inline]
2009 pub fn node_runtime(&self) -> Option<&NodeRuntime> {
2010 self.node.as_ref()
2011 }
2012
2013 #[inline]
2014 pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
2015 self.buffer_store.read(cx).buffers().collect()
2016 }
2017
2018 #[inline]
2019 pub fn environment(&self) -> &Entity<ProjectEnvironment> {
2020 &self.environment
2021 }
2022
2023 #[inline]
2024 pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
2025 self.environment.read(cx).get_cli_environment()
2026 }
2027
2028 #[inline]
2029 pub fn peek_environment_error<'a>(&'a self, cx: &'a App) -> Option<&'a String> {
2030 self.environment.read(cx).peek_environment_error()
2031 }
2032
2033 #[inline]
2034 pub fn pop_environment_error(&mut self, cx: &mut Context<Self>) {
2035 self.environment.update(cx, |environment, _| {
2036 environment.pop_environment_error();
2037 });
2038 }
2039
2040 #[cfg(any(test, feature = "test-support"))]
2041 #[inline]
2042 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
2043 self.buffer_store
2044 .read(cx)
2045 .get_by_path(&path.into())
2046 .is_some()
2047 }
2048
2049 #[inline]
2050 pub fn fs(&self) -> &Arc<dyn Fs> {
2051 &self.fs
2052 }
2053
2054 #[inline]
2055 pub fn remote_id(&self) -> Option<u64> {
2056 match self.client_state {
2057 ProjectClientState::Local => None,
2058 ProjectClientState::Shared { remote_id, .. }
2059 | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
2060 }
2061 }
2062
2063 #[inline]
2064 pub fn supports_terminal(&self, _cx: &App) -> bool {
2065 if self.is_local() {
2066 return true;
2067 }
2068 if self.is_via_remote_server() {
2069 return true;
2070 }
2071
2072 false
2073 }
2074
2075 #[inline]
2076 pub fn remote_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
2077 self.remote_client
2078 .as_ref()
2079 .map(|remote| remote.read(cx).connection_state())
2080 }
2081
2082 #[inline]
2083 pub fn remote_connection_options(&self, cx: &App) -> Option<RemoteConnectionOptions> {
2084 self.remote_client
2085 .as_ref()
2086 .map(|remote| remote.read(cx).connection_options())
2087 }
2088
2089 #[inline]
2090 pub fn replica_id(&self) -> ReplicaId {
2091 match self.client_state {
2092 ProjectClientState::Remote { replica_id, .. } => replica_id,
2093 _ => {
2094 if self.remote_client.is_some() {
2095 ReplicaId::REMOTE_SERVER
2096 } else {
2097 ReplicaId::LOCAL
2098 }
2099 }
2100 }
2101 }
2102
2103 #[inline]
2104 pub fn task_store(&self) -> &Entity<TaskStore> {
2105 &self.task_store
2106 }
2107
2108 #[inline]
2109 pub fn snippets(&self) -> &Entity<SnippetProvider> {
2110 &self.snippets
2111 }
2112
2113 #[inline]
2114 pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
2115 match kind {
2116 SearchInputKind::Query => &self.search_history,
2117 SearchInputKind::Include => &self.search_included_history,
2118 SearchInputKind::Exclude => &self.search_excluded_history,
2119 }
2120 }
2121
2122 #[inline]
2123 pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
2124 match kind {
2125 SearchInputKind::Query => &mut self.search_history,
2126 SearchInputKind::Include => &mut self.search_included_history,
2127 SearchInputKind::Exclude => &mut self.search_excluded_history,
2128 }
2129 }
2130
2131 #[inline]
2132 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
2133 &self.collaborators
2134 }
2135
2136 #[inline]
2137 pub fn host(&self) -> Option<&Collaborator> {
2138 self.collaborators.values().find(|c| c.is_host)
2139 }
2140
2141 #[inline]
2142 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
2143 self.worktree_store.update(cx, |store, _| {
2144 store.set_worktrees_reordered(worktrees_reordered);
2145 });
2146 }
2147
2148 /// Collect all worktrees, including ones that don't appear in the project panel
2149 #[inline]
2150 pub fn worktrees<'a>(
2151 &self,
2152 cx: &'a App,
2153 ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2154 self.worktree_store.read(cx).worktrees()
2155 }
2156
2157 /// Collect all user-visible worktrees, the ones that appear in the project panel.
2158 #[inline]
2159 pub fn visible_worktrees<'a>(
2160 &'a self,
2161 cx: &'a App,
2162 ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2163 self.worktree_store.read(cx).visible_worktrees(cx)
2164 }
2165
2166 #[inline]
2167 pub fn worktree_for_root_name(&self, root_name: &str, cx: &App) -> Option<Entity<Worktree>> {
2168 self.visible_worktrees(cx)
2169 .find(|tree| tree.read(cx).root_name() == root_name)
2170 }
2171
2172 #[inline]
2173 pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
2174 self.visible_worktrees(cx)
2175 .map(|tree| tree.read(cx).root_name().as_unix_str())
2176 }
2177
2178 #[inline]
2179 pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
2180 self.worktree_store.read(cx).worktree_for_id(id, cx)
2181 }
2182
2183 pub fn worktree_for_entry(
2184 &self,
2185 entry_id: ProjectEntryId,
2186 cx: &App,
2187 ) -> Option<Entity<Worktree>> {
2188 self.worktree_store
2189 .read(cx)
2190 .worktree_for_entry(entry_id, cx)
2191 }
2192
2193 #[inline]
2194 pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
2195 self.worktree_for_entry(entry_id, cx)
2196 .map(|worktree| worktree.read(cx).id())
2197 }
2198
2199 /// Checks if the entry is the root of a worktree.
2200 #[inline]
2201 pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
2202 self.worktree_for_entry(entry_id, cx)
2203 .map(|worktree| {
2204 worktree
2205 .read(cx)
2206 .root_entry()
2207 .is_some_and(|e| e.id == entry_id)
2208 })
2209 .unwrap_or(false)
2210 }
2211
2212 #[inline]
2213 pub fn project_path_git_status(
2214 &self,
2215 project_path: &ProjectPath,
2216 cx: &App,
2217 ) -> Option<FileStatus> {
2218 self.git_store
2219 .read(cx)
2220 .project_path_git_status(project_path, cx)
2221 }
2222
2223 #[inline]
2224 pub fn visibility_for_paths(
2225 &self,
2226 paths: &[PathBuf],
2227 metadatas: &[Metadata],
2228 exclude_sub_dirs: bool,
2229 cx: &App,
2230 ) -> Option<bool> {
2231 paths
2232 .iter()
2233 .zip(metadatas)
2234 .map(|(path, metadata)| self.visibility_for_path(path, metadata, exclude_sub_dirs, cx))
2235 .max()
2236 .flatten()
2237 }
2238
2239 pub fn visibility_for_path(
2240 &self,
2241 path: &Path,
2242 metadata: &Metadata,
2243 exclude_sub_dirs: bool,
2244 cx: &App,
2245 ) -> Option<bool> {
2246 let path = SanitizedPath::new(path).as_path();
2247 self.worktrees(cx)
2248 .filter_map(|worktree| {
2249 let worktree = worktree.read(cx);
2250 let abs_path = worktree.as_local()?.abs_path();
2251 let contains = path == abs_path.as_ref()
2252 || (path.starts_with(abs_path) && (!exclude_sub_dirs || !metadata.is_dir));
2253 contains.then(|| worktree.is_visible())
2254 })
2255 .max()
2256 }
2257
2258 pub fn create_entry(
2259 &mut self,
2260 project_path: impl Into<ProjectPath>,
2261 is_directory: bool,
2262 cx: &mut Context<Self>,
2263 ) -> Task<Result<CreatedEntry>> {
2264 let project_path = project_path.into();
2265 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
2266 return Task::ready(Err(anyhow!(format!(
2267 "No worktree for path {project_path:?}"
2268 ))));
2269 };
2270 worktree.update(cx, |worktree, cx| {
2271 worktree.create_entry(project_path.path, is_directory, None, cx)
2272 })
2273 }
2274
2275 #[inline]
2276 pub fn copy_entry(
2277 &mut self,
2278 entry_id: ProjectEntryId,
2279 new_project_path: ProjectPath,
2280 cx: &mut Context<Self>,
2281 ) -> Task<Result<Option<Entry>>> {
2282 self.worktree_store.update(cx, |worktree_store, cx| {
2283 worktree_store.copy_entry(entry_id, new_project_path, cx)
2284 })
2285 }
2286
2287 /// Renames the project entry with given `entry_id`.
2288 ///
2289 /// `new_path` is a relative path to worktree root.
2290 /// If root entry is renamed then its new root name is used instead.
2291 pub fn rename_entry(
2292 &mut self,
2293 entry_id: ProjectEntryId,
2294 new_path: ProjectPath,
2295 cx: &mut Context<Self>,
2296 ) -> Task<Result<CreatedEntry>> {
2297 let worktree_store = self.worktree_store.clone();
2298 let Some((worktree, old_path, is_dir)) = worktree_store
2299 .read(cx)
2300 .worktree_and_entry_for_id(entry_id, cx)
2301 .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
2302 else {
2303 return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
2304 };
2305
2306 let worktree_id = worktree.read(cx).id();
2307 let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
2308
2309 let lsp_store = self.lsp_store().downgrade();
2310 cx.spawn(async move |project, cx| {
2311 let (old_abs_path, new_abs_path) = {
2312 let root_path = worktree.read_with(cx, |this, _| this.abs_path())?;
2313 let new_abs_path = if is_root_entry {
2314 root_path
2315 .parent()
2316 .unwrap()
2317 .join(new_path.path.as_std_path())
2318 } else {
2319 root_path.join(&new_path.path.as_std_path())
2320 };
2321 (root_path.join(old_path.as_std_path()), new_abs_path)
2322 };
2323 let transaction = LspStore::will_rename_entry(
2324 lsp_store.clone(),
2325 worktree_id,
2326 &old_abs_path,
2327 &new_abs_path,
2328 is_dir,
2329 cx.clone(),
2330 )
2331 .await;
2332
2333 let entry = worktree_store
2334 .update(cx, |worktree_store, cx| {
2335 worktree_store.rename_entry(entry_id, new_path.clone(), cx)
2336 })?
2337 .await?;
2338
2339 project
2340 .update(cx, |_, cx| {
2341 cx.emit(Event::EntryRenamed(
2342 transaction,
2343 new_path.clone(),
2344 new_abs_path.clone(),
2345 ));
2346 })
2347 .ok();
2348
2349 lsp_store
2350 .read_with(cx, |this, _| {
2351 this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
2352 })
2353 .ok();
2354 Ok(entry)
2355 })
2356 }
2357
2358 #[inline]
2359 pub fn delete_file(
2360 &mut self,
2361 path: ProjectPath,
2362 trash: bool,
2363 cx: &mut Context<Self>,
2364 ) -> Option<Task<Result<()>>> {
2365 let entry = self.entry_for_path(&path, cx)?;
2366 self.delete_entry(entry.id, trash, cx)
2367 }
2368
2369 #[inline]
2370 pub fn delete_entry(
2371 &mut self,
2372 entry_id: ProjectEntryId,
2373 trash: bool,
2374 cx: &mut Context<Self>,
2375 ) -> Option<Task<Result<()>>> {
2376 let worktree = self.worktree_for_entry(entry_id, cx)?;
2377 cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
2378 worktree.update(cx, |worktree, cx| {
2379 worktree.delete_entry(entry_id, trash, cx)
2380 })
2381 }
2382
2383 #[inline]
2384 pub fn expand_entry(
2385 &mut self,
2386 worktree_id: WorktreeId,
2387 entry_id: ProjectEntryId,
2388 cx: &mut Context<Self>,
2389 ) -> Option<Task<Result<()>>> {
2390 let worktree = self.worktree_for_id(worktree_id, cx)?;
2391 worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
2392 }
2393
2394 pub fn expand_all_for_entry(
2395 &mut self,
2396 worktree_id: WorktreeId,
2397 entry_id: ProjectEntryId,
2398 cx: &mut Context<Self>,
2399 ) -> Option<Task<Result<()>>> {
2400 let worktree = self.worktree_for_id(worktree_id, cx)?;
2401 let task = worktree.update(cx, |worktree, cx| {
2402 worktree.expand_all_for_entry(entry_id, cx)
2403 });
2404 Some(cx.spawn(async move |this, cx| {
2405 task.context("no task")?.await?;
2406 this.update(cx, |_, cx| {
2407 cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
2408 })?;
2409 Ok(())
2410 }))
2411 }
2412
2413 pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2414 anyhow::ensure!(
2415 matches!(self.client_state, ProjectClientState::Local),
2416 "project was already shared"
2417 );
2418
2419 self.client_subscriptions.extend([
2420 self.collab_client
2421 .subscribe_to_entity(project_id)?
2422 .set_entity(&cx.entity(), &cx.to_async()),
2423 self.collab_client
2424 .subscribe_to_entity(project_id)?
2425 .set_entity(&self.worktree_store, &cx.to_async()),
2426 self.collab_client
2427 .subscribe_to_entity(project_id)?
2428 .set_entity(&self.buffer_store, &cx.to_async()),
2429 self.collab_client
2430 .subscribe_to_entity(project_id)?
2431 .set_entity(&self.lsp_store, &cx.to_async()),
2432 self.collab_client
2433 .subscribe_to_entity(project_id)?
2434 .set_entity(&self.settings_observer, &cx.to_async()),
2435 self.collab_client
2436 .subscribe_to_entity(project_id)?
2437 .set_entity(&self.dap_store, &cx.to_async()),
2438 self.collab_client
2439 .subscribe_to_entity(project_id)?
2440 .set_entity(&self.breakpoint_store, &cx.to_async()),
2441 self.collab_client
2442 .subscribe_to_entity(project_id)?
2443 .set_entity(&self.git_store, &cx.to_async()),
2444 ]);
2445
2446 self.buffer_store.update(cx, |buffer_store, cx| {
2447 buffer_store.shared(project_id, self.collab_client.clone().into(), cx)
2448 });
2449 self.worktree_store.update(cx, |worktree_store, cx| {
2450 worktree_store.shared(project_id, self.collab_client.clone().into(), cx);
2451 });
2452 self.lsp_store.update(cx, |lsp_store, cx| {
2453 lsp_store.shared(project_id, self.collab_client.clone().into(), cx)
2454 });
2455 self.breakpoint_store.update(cx, |breakpoint_store, _| {
2456 breakpoint_store.shared(project_id, self.collab_client.clone().into())
2457 });
2458 self.dap_store.update(cx, |dap_store, cx| {
2459 dap_store.shared(project_id, self.collab_client.clone().into(), cx);
2460 });
2461 self.task_store.update(cx, |task_store, cx| {
2462 task_store.shared(project_id, self.collab_client.clone().into(), cx);
2463 });
2464 self.settings_observer.update(cx, |settings_observer, cx| {
2465 settings_observer.shared(project_id, self.collab_client.clone().into(), cx)
2466 });
2467 self.git_store.update(cx, |git_store, cx| {
2468 git_store.shared(project_id, self.collab_client.clone().into(), cx)
2469 });
2470
2471 self.client_state = ProjectClientState::Shared {
2472 remote_id: project_id,
2473 };
2474
2475 cx.emit(Event::RemoteIdChanged(Some(project_id)));
2476 Ok(())
2477 }
2478
2479 pub fn reshared(
2480 &mut self,
2481 message: proto::ResharedProject,
2482 cx: &mut Context<Self>,
2483 ) -> Result<()> {
2484 self.buffer_store
2485 .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2486 self.set_collaborators_from_proto(message.collaborators, cx)?;
2487
2488 self.worktree_store.update(cx, |worktree_store, cx| {
2489 worktree_store.send_project_updates(cx);
2490 });
2491 if let Some(remote_id) = self.remote_id() {
2492 self.git_store.update(cx, |git_store, cx| {
2493 git_store.shared(remote_id, self.collab_client.clone().into(), cx)
2494 });
2495 }
2496 cx.emit(Event::Reshared);
2497 Ok(())
2498 }
2499
2500 pub fn rejoined(
2501 &mut self,
2502 message: proto::RejoinedProject,
2503 message_id: u32,
2504 cx: &mut Context<Self>,
2505 ) -> Result<()> {
2506 cx.update_global::<SettingsStore, _>(|store, cx| {
2507 for worktree_metadata in &message.worktrees {
2508 store
2509 .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
2510 .log_err();
2511 }
2512 });
2513
2514 self.join_project_response_message_id = message_id;
2515 self.set_worktrees_from_proto(message.worktrees, cx)?;
2516 self.set_collaborators_from_proto(message.collaborators, cx)?;
2517
2518 let project = cx.weak_entity();
2519 self.lsp_store.update(cx, |lsp_store, cx| {
2520 lsp_store.set_language_server_statuses_from_proto(
2521 project,
2522 message.language_servers,
2523 message.language_server_capabilities,
2524 cx,
2525 )
2526 });
2527 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2528 .unwrap();
2529 cx.emit(Event::Rejoined);
2530 Ok(())
2531 }
2532
2533 #[inline]
2534 pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2535 self.unshare_internal(cx)?;
2536 cx.emit(Event::RemoteIdChanged(None));
2537 Ok(())
2538 }
2539
2540 fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2541 anyhow::ensure!(
2542 !self.is_via_collab(),
2543 "attempted to unshare a remote project"
2544 );
2545
2546 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2547 self.client_state = ProjectClientState::Local;
2548 self.collaborators.clear();
2549 self.client_subscriptions.clear();
2550 self.worktree_store.update(cx, |store, cx| {
2551 store.unshared(cx);
2552 });
2553 self.buffer_store.update(cx, |buffer_store, cx| {
2554 buffer_store.forget_shared_buffers();
2555 buffer_store.unshared(cx)
2556 });
2557 self.task_store.update(cx, |task_store, cx| {
2558 task_store.unshared(cx);
2559 });
2560 self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2561 breakpoint_store.unshared(cx);
2562 });
2563 self.dap_store.update(cx, |dap_store, cx| {
2564 dap_store.unshared(cx);
2565 });
2566 self.settings_observer.update(cx, |settings_observer, cx| {
2567 settings_observer.unshared(cx);
2568 });
2569 self.git_store.update(cx, |git_store, cx| {
2570 git_store.unshared(cx);
2571 });
2572
2573 self.collab_client
2574 .send(proto::UnshareProject {
2575 project_id: remote_id,
2576 })
2577 .ok();
2578 Ok(())
2579 } else {
2580 anyhow::bail!("attempted to unshare an unshared project");
2581 }
2582 }
2583
2584 pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2585 if self.is_disconnected(cx) {
2586 return;
2587 }
2588 self.disconnected_from_host_internal(cx);
2589 cx.emit(Event::DisconnectedFromHost);
2590 }
2591
2592 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2593 let new_capability =
2594 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2595 Capability::ReadWrite
2596 } else {
2597 Capability::ReadOnly
2598 };
2599 if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
2600 if *capability == new_capability {
2601 return;
2602 }
2603
2604 *capability = new_capability;
2605 for buffer in self.opened_buffers(cx) {
2606 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2607 }
2608 }
2609 }
2610
2611 fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2612 if let ProjectClientState::Remote {
2613 sharing_has_stopped,
2614 ..
2615 } = &mut self.client_state
2616 {
2617 *sharing_has_stopped = true;
2618 self.collaborators.clear();
2619 self.worktree_store.update(cx, |store, cx| {
2620 store.disconnected_from_host(cx);
2621 });
2622 self.buffer_store.update(cx, |buffer_store, cx| {
2623 buffer_store.disconnected_from_host(cx)
2624 });
2625 self.lsp_store
2626 .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2627 }
2628 }
2629
2630 #[inline]
2631 pub fn close(&mut self, cx: &mut Context<Self>) {
2632 cx.emit(Event::Closed);
2633 }
2634
2635 #[inline]
2636 pub fn is_disconnected(&self, cx: &App) -> bool {
2637 match &self.client_state {
2638 ProjectClientState::Remote {
2639 sharing_has_stopped,
2640 ..
2641 } => *sharing_has_stopped,
2642 ProjectClientState::Local if self.is_via_remote_server() => {
2643 self.remote_client_is_disconnected(cx)
2644 }
2645 _ => false,
2646 }
2647 }
2648
2649 #[inline]
2650 fn remote_client_is_disconnected(&self, cx: &App) -> bool {
2651 self.remote_client
2652 .as_ref()
2653 .map(|remote| remote.read(cx).is_disconnected())
2654 .unwrap_or(false)
2655 }
2656
2657 #[inline]
2658 pub fn capability(&self) -> Capability {
2659 match &self.client_state {
2660 ProjectClientState::Remote { capability, .. } => *capability,
2661 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2662 }
2663 }
2664
2665 #[inline]
2666 pub fn is_read_only(&self, cx: &App) -> bool {
2667 self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
2668 }
2669
2670 #[inline]
2671 pub fn is_local(&self) -> bool {
2672 match &self.client_state {
2673 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2674 self.remote_client.is_none()
2675 }
2676 ProjectClientState::Remote { .. } => false,
2677 }
2678 }
2679
2680 /// Whether this project is a remote server (not counting collab).
2681 #[inline]
2682 pub fn is_via_remote_server(&self) -> bool {
2683 match &self.client_state {
2684 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2685 self.remote_client.is_some()
2686 }
2687 ProjectClientState::Remote { .. } => false,
2688 }
2689 }
2690
2691 /// Whether this project is from collab (not counting remote servers).
2692 #[inline]
2693 pub fn is_via_collab(&self) -> bool {
2694 match &self.client_state {
2695 ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2696 ProjectClientState::Remote { .. } => true,
2697 }
2698 }
2699
2700 /// `!self.is_local()`
2701 #[inline]
2702 pub fn is_remote(&self) -> bool {
2703 debug_assert_eq!(
2704 !self.is_local(),
2705 self.is_via_collab() || self.is_via_remote_server()
2706 );
2707 !self.is_local()
2708 }
2709
2710 pub fn disable_worktree_scanner(&mut self, cx: &mut Context<Self>) {
2711 self.worktree_store.update(cx, |worktree_store, _cx| {
2712 worktree_store.disable_scanner();
2713 });
2714 }
2715
2716 #[inline]
2717 pub fn create_buffer(
2718 &mut self,
2719 searchable: bool,
2720 cx: &mut Context<Self>,
2721 ) -> Task<Result<Entity<Buffer>>> {
2722 self.buffer_store.update(cx, |buffer_store, cx| {
2723 buffer_store.create_buffer(searchable, cx)
2724 })
2725 }
2726
2727 #[inline]
2728 pub fn create_local_buffer(
2729 &mut self,
2730 text: &str,
2731 language: Option<Arc<Language>>,
2732 project_searchable: bool,
2733 cx: &mut Context<Self>,
2734 ) -> Entity<Buffer> {
2735 if self.is_remote() {
2736 panic!("called create_local_buffer on a remote project")
2737 }
2738 self.buffer_store.update(cx, |buffer_store, cx| {
2739 buffer_store.create_local_buffer(text, language, project_searchable, cx)
2740 })
2741 }
2742
2743 pub fn open_path(
2744 &mut self,
2745 path: ProjectPath,
2746 cx: &mut Context<Self>,
2747 ) -> Task<Result<(Option<ProjectEntryId>, Entity<Buffer>)>> {
2748 let task = self.open_buffer(path, cx);
2749 cx.spawn(async move |_project, cx| {
2750 let buffer = task.await?;
2751 let project_entry_id = buffer.read_with(cx, |buffer, _cx| {
2752 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id())
2753 })?;
2754
2755 Ok((project_entry_id, buffer))
2756 })
2757 }
2758
2759 pub fn open_local_buffer(
2760 &mut self,
2761 abs_path: impl AsRef<Path>,
2762 cx: &mut Context<Self>,
2763 ) -> Task<Result<Entity<Buffer>>> {
2764 let worktree_task = self.find_or_create_worktree(abs_path.as_ref(), false, cx);
2765 cx.spawn(async move |this, cx| {
2766 let (worktree, relative_path) = worktree_task.await?;
2767 this.update(cx, |this, cx| {
2768 this.open_buffer((worktree.read(cx).id(), relative_path), cx)
2769 })?
2770 .await
2771 })
2772 }
2773
2774 #[cfg(any(test, feature = "test-support"))]
2775 pub fn open_local_buffer_with_lsp(
2776 &mut self,
2777 abs_path: impl AsRef<Path>,
2778 cx: &mut Context<Self>,
2779 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2780 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2781 self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
2782 } else {
2783 Task::ready(Err(anyhow!("no such path")))
2784 }
2785 }
2786
2787 pub fn open_buffer(
2788 &mut self,
2789 path: impl Into<ProjectPath>,
2790 cx: &mut App,
2791 ) -> Task<Result<Entity<Buffer>>> {
2792 if self.is_disconnected(cx) {
2793 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2794 }
2795
2796 self.buffer_store.update(cx, |buffer_store, cx| {
2797 buffer_store.open_buffer(path.into(), cx)
2798 })
2799 }
2800
2801 #[cfg(any(test, feature = "test-support"))]
2802 pub fn open_buffer_with_lsp(
2803 &mut self,
2804 path: impl Into<ProjectPath>,
2805 cx: &mut Context<Self>,
2806 ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2807 let buffer = self.open_buffer(path, cx);
2808 cx.spawn(async move |this, cx| {
2809 let buffer = buffer.await?;
2810 let handle = this.update(cx, |project, cx| {
2811 project.register_buffer_with_language_servers(&buffer, cx)
2812 })?;
2813 Ok((buffer, handle))
2814 })
2815 }
2816
2817 pub fn register_buffer_with_language_servers(
2818 &self,
2819 buffer: &Entity<Buffer>,
2820 cx: &mut App,
2821 ) -> OpenLspBufferHandle {
2822 self.lsp_store.update(cx, |lsp_store, cx| {
2823 lsp_store.register_buffer_with_language_servers(buffer, HashSet::default(), false, cx)
2824 })
2825 }
2826
2827 pub fn open_unstaged_diff(
2828 &mut self,
2829 buffer: Entity<Buffer>,
2830 cx: &mut Context<Self>,
2831 ) -> Task<Result<Entity<BufferDiff>>> {
2832 if self.is_disconnected(cx) {
2833 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2834 }
2835 self.git_store
2836 .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
2837 }
2838
2839 pub fn open_uncommitted_diff(
2840 &mut self,
2841 buffer: Entity<Buffer>,
2842 cx: &mut Context<Self>,
2843 ) -> Task<Result<Entity<BufferDiff>>> {
2844 if self.is_disconnected(cx) {
2845 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2846 }
2847 self.git_store.update(cx, |git_store, cx| {
2848 git_store.open_uncommitted_diff(buffer, cx)
2849 })
2850 }
2851
2852 pub fn open_buffer_by_id(
2853 &mut self,
2854 id: BufferId,
2855 cx: &mut Context<Self>,
2856 ) -> Task<Result<Entity<Buffer>>> {
2857 if let Some(buffer) = self.buffer_for_id(id, cx) {
2858 Task::ready(Ok(buffer))
2859 } else if self.is_local() || self.is_via_remote_server() {
2860 Task::ready(Err(anyhow!("buffer {id} does not exist")))
2861 } else if let Some(project_id) = self.remote_id() {
2862 let request = self.collab_client.request(proto::OpenBufferById {
2863 project_id,
2864 id: id.into(),
2865 });
2866 cx.spawn(async move |project, cx| {
2867 let buffer_id = BufferId::new(request.await?.buffer_id)?;
2868 project
2869 .update(cx, |project, cx| {
2870 project.buffer_store.update(cx, |buffer_store, cx| {
2871 buffer_store.wait_for_remote_buffer(buffer_id, cx)
2872 })
2873 })?
2874 .await
2875 })
2876 } else {
2877 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2878 }
2879 }
2880
2881 pub fn save_buffers(
2882 &self,
2883 buffers: HashSet<Entity<Buffer>>,
2884 cx: &mut Context<Self>,
2885 ) -> Task<Result<()>> {
2886 cx.spawn(async move |this, cx| {
2887 let save_tasks = buffers.into_iter().filter_map(|buffer| {
2888 this.update(cx, |this, cx| this.save_buffer(buffer, cx))
2889 .ok()
2890 });
2891 try_join_all(save_tasks).await?;
2892 Ok(())
2893 })
2894 }
2895
2896 pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2897 self.buffer_store
2898 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2899 }
2900
2901 pub fn save_buffer_as(
2902 &mut self,
2903 buffer: Entity<Buffer>,
2904 path: ProjectPath,
2905 cx: &mut Context<Self>,
2906 ) -> Task<Result<()>> {
2907 self.buffer_store.update(cx, |buffer_store, cx| {
2908 buffer_store.save_buffer_as(buffer.clone(), path, cx)
2909 })
2910 }
2911
2912 pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2913 self.buffer_store.read(cx).get_by_path(path)
2914 }
2915
2916 fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2917 {
2918 let mut remotely_created_models = self.remotely_created_models.lock();
2919 if remotely_created_models.retain_count > 0 {
2920 remotely_created_models.buffers.push(buffer.clone())
2921 }
2922 }
2923
2924 self.request_buffer_diff_recalculation(buffer, cx);
2925
2926 cx.subscribe(buffer, |this, buffer, event, cx| {
2927 this.on_buffer_event(buffer, event, cx);
2928 })
2929 .detach();
2930
2931 Ok(())
2932 }
2933
2934 pub fn open_image(
2935 &mut self,
2936 path: impl Into<ProjectPath>,
2937 cx: &mut Context<Self>,
2938 ) -> Task<Result<Entity<ImageItem>>> {
2939 if self.is_disconnected(cx) {
2940 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2941 }
2942
2943 let open_image_task = self.image_store.update(cx, |image_store, cx| {
2944 image_store.open_image(path.into(), cx)
2945 });
2946
2947 let weak_project = cx.entity().downgrade();
2948 cx.spawn(async move |_, cx| {
2949 let image_item = open_image_task.await?;
2950
2951 // Check if metadata already exists (e.g., for remote images)
2952 let needs_metadata =
2953 cx.read_entity(&image_item, |item, _| item.image_metadata.is_none())?;
2954
2955 if needs_metadata {
2956 let project = weak_project.upgrade().context("Project dropped")?;
2957 let metadata =
2958 ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
2959 image_item.update(cx, |image_item, cx| {
2960 image_item.image_metadata = Some(metadata);
2961 cx.emit(ImageItemEvent::MetadataUpdated);
2962 })?;
2963 }
2964
2965 Ok(image_item)
2966 })
2967 }
2968
2969 async fn send_buffer_ordered_messages(
2970 project: WeakEntity<Self>,
2971 rx: UnboundedReceiver<BufferOrderedMessage>,
2972 cx: &mut AsyncApp,
2973 ) -> Result<()> {
2974 const MAX_BATCH_SIZE: usize = 128;
2975
2976 let mut operations_by_buffer_id = HashMap::default();
2977 async fn flush_operations(
2978 this: &WeakEntity<Project>,
2979 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2980 needs_resync_with_host: &mut bool,
2981 is_local: bool,
2982 cx: &mut AsyncApp,
2983 ) -> Result<()> {
2984 for (buffer_id, operations) in operations_by_buffer_id.drain() {
2985 let request = this.read_with(cx, |this, _| {
2986 let project_id = this.remote_id()?;
2987 Some(this.collab_client.request(proto::UpdateBuffer {
2988 buffer_id: buffer_id.into(),
2989 project_id,
2990 operations,
2991 }))
2992 })?;
2993 if let Some(request) = request
2994 && request.await.is_err()
2995 && !is_local
2996 {
2997 *needs_resync_with_host = true;
2998 break;
2999 }
3000 }
3001 Ok(())
3002 }
3003
3004 let mut needs_resync_with_host = false;
3005 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
3006
3007 while let Some(changes) = changes.next().await {
3008 let is_local = project.read_with(cx, |this, _| this.is_local())?;
3009
3010 for change in changes {
3011 match change {
3012 BufferOrderedMessage::Operation {
3013 buffer_id,
3014 operation,
3015 } => {
3016 if needs_resync_with_host {
3017 continue;
3018 }
3019
3020 operations_by_buffer_id
3021 .entry(buffer_id)
3022 .or_insert(Vec::new())
3023 .push(operation);
3024 }
3025
3026 BufferOrderedMessage::Resync => {
3027 operations_by_buffer_id.clear();
3028 if project
3029 .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
3030 .await
3031 .is_ok()
3032 {
3033 needs_resync_with_host = false;
3034 }
3035 }
3036
3037 BufferOrderedMessage::LanguageServerUpdate {
3038 language_server_id,
3039 message,
3040 name,
3041 } => {
3042 flush_operations(
3043 &project,
3044 &mut operations_by_buffer_id,
3045 &mut needs_resync_with_host,
3046 is_local,
3047 cx,
3048 )
3049 .await?;
3050
3051 project.read_with(cx, |project, _| {
3052 if let Some(project_id) = project.remote_id() {
3053 project
3054 .collab_client
3055 .send(proto::UpdateLanguageServer {
3056 project_id,
3057 server_name: name.map(|name| String::from(name.0)),
3058 language_server_id: language_server_id.to_proto(),
3059 variant: Some(message),
3060 })
3061 .log_err();
3062 }
3063 })?;
3064 }
3065 }
3066 }
3067
3068 flush_operations(
3069 &project,
3070 &mut operations_by_buffer_id,
3071 &mut needs_resync_with_host,
3072 is_local,
3073 cx,
3074 )
3075 .await?;
3076 }
3077
3078 Ok(())
3079 }
3080
3081 fn on_buffer_store_event(
3082 &mut self,
3083 _: Entity<BufferStore>,
3084 event: &BufferStoreEvent,
3085 cx: &mut Context<Self>,
3086 ) {
3087 match event {
3088 BufferStoreEvent::BufferAdded(buffer) => {
3089 self.register_buffer(buffer, cx).log_err();
3090 }
3091 BufferStoreEvent::BufferDropped(buffer_id) => {
3092 if let Some(ref remote_client) = self.remote_client {
3093 remote_client
3094 .read(cx)
3095 .proto_client()
3096 .send(proto::CloseBuffer {
3097 project_id: 0,
3098 buffer_id: buffer_id.to_proto(),
3099 })
3100 .log_err();
3101 }
3102 }
3103 _ => {}
3104 }
3105 }
3106
3107 fn on_image_store_event(
3108 &mut self,
3109 _: Entity<ImageStore>,
3110 event: &ImageStoreEvent,
3111 cx: &mut Context<Self>,
3112 ) {
3113 match event {
3114 ImageStoreEvent::ImageAdded(image) => {
3115 cx.subscribe(image, |this, image, event, cx| {
3116 this.on_image_event(image, event, cx);
3117 })
3118 .detach();
3119 }
3120 }
3121 }
3122
3123 fn on_dap_store_event(
3124 &mut self,
3125 _: Entity<DapStore>,
3126 event: &DapStoreEvent,
3127 cx: &mut Context<Self>,
3128 ) {
3129 if let DapStoreEvent::Notification(message) = event {
3130 cx.emit(Event::Toast {
3131 notification_id: "dap".into(),
3132 message: message.clone(),
3133 });
3134 }
3135 }
3136
3137 fn on_lsp_store_event(
3138 &mut self,
3139 _: Entity<LspStore>,
3140 event: &LspStoreEvent,
3141 cx: &mut Context<Self>,
3142 ) {
3143 match event {
3144 LspStoreEvent::DiagnosticsUpdated { server_id, paths } => {
3145 cx.emit(Event::DiagnosticsUpdated {
3146 paths: paths.clone(),
3147 language_server_id: *server_id,
3148 })
3149 }
3150 LspStoreEvent::LanguageServerAdded(server_id, name, worktree_id) => cx.emit(
3151 Event::LanguageServerAdded(*server_id, name.clone(), *worktree_id),
3152 ),
3153 LspStoreEvent::LanguageServerRemoved(server_id) => {
3154 cx.emit(Event::LanguageServerRemoved(*server_id))
3155 }
3156 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
3157 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
3158 ),
3159 LspStoreEvent::LanguageDetected {
3160 buffer,
3161 new_language,
3162 } => {
3163 let Some(_) = new_language else {
3164 cx.emit(Event::LanguageNotFound(buffer.clone()));
3165 return;
3166 };
3167 }
3168 LspStoreEvent::RefreshInlayHints {
3169 server_id,
3170 request_id,
3171 } => cx.emit(Event::RefreshInlayHints {
3172 server_id: *server_id,
3173 request_id: *request_id,
3174 }),
3175 LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
3176 LspStoreEvent::LanguageServerPrompt(prompt) => {
3177 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
3178 }
3179 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
3180 cx.emit(Event::DiskBasedDiagnosticsStarted {
3181 language_server_id: *language_server_id,
3182 });
3183 }
3184 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
3185 cx.emit(Event::DiskBasedDiagnosticsFinished {
3186 language_server_id: *language_server_id,
3187 });
3188 }
3189 LspStoreEvent::LanguageServerUpdate {
3190 language_server_id,
3191 name,
3192 message,
3193 } => {
3194 if self.is_local() {
3195 self.enqueue_buffer_ordered_message(
3196 BufferOrderedMessage::LanguageServerUpdate {
3197 language_server_id: *language_server_id,
3198 message: message.clone(),
3199 name: name.clone(),
3200 },
3201 )
3202 .ok();
3203 }
3204
3205 match message {
3206 proto::update_language_server::Variant::MetadataUpdated(update) => {
3207 self.lsp_store.update(cx, |lsp_store, _| {
3208 if let Some(capabilities) = update
3209 .capabilities
3210 .as_ref()
3211 .and_then(|capabilities| serde_json::from_str(capabilities).ok())
3212 {
3213 lsp_store
3214 .lsp_server_capabilities
3215 .insert(*language_server_id, capabilities);
3216 }
3217
3218 if let Some(language_server_status) = lsp_store
3219 .language_server_statuses
3220 .get_mut(language_server_id)
3221 {
3222 if let Some(binary) = &update.binary {
3223 language_server_status.binary = Some(LanguageServerBinary {
3224 path: PathBuf::from(&binary.path),
3225 arguments: binary
3226 .arguments
3227 .iter()
3228 .map(OsString::from)
3229 .collect(),
3230 env: None,
3231 });
3232 }
3233
3234 language_server_status.configuration = update
3235 .configuration
3236 .as_ref()
3237 .and_then(|config_str| serde_json::from_str(config_str).ok());
3238
3239 language_server_status.workspace_folders = update
3240 .workspace_folders
3241 .iter()
3242 .filter_map(|uri_str| lsp::Uri::from_str(uri_str).ok())
3243 .collect();
3244 }
3245 });
3246 }
3247 proto::update_language_server::Variant::RegisteredForBuffer(update) => {
3248 if let Some(buffer_id) = BufferId::new(update.buffer_id).ok() {
3249 cx.emit(Event::LanguageServerBufferRegistered {
3250 buffer_id,
3251 server_id: *language_server_id,
3252 buffer_abs_path: PathBuf::from(&update.buffer_abs_path),
3253 name: name.clone(),
3254 });
3255 }
3256 }
3257 _ => (),
3258 }
3259 }
3260 LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
3261 notification_id: "lsp".into(),
3262 message: message.clone(),
3263 }),
3264 LspStoreEvent::SnippetEdit {
3265 buffer_id,
3266 edits,
3267 most_recent_edit,
3268 } => {
3269 if most_recent_edit.replica_id == self.replica_id() {
3270 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
3271 }
3272 }
3273 LspStoreEvent::WorkspaceEditApplied(transaction) => {
3274 cx.emit(Event::WorkspaceEditApplied(transaction.clone()))
3275 }
3276 }
3277 }
3278
3279 fn on_remote_client_event(
3280 &mut self,
3281 _: Entity<RemoteClient>,
3282 event: &remote::RemoteClientEvent,
3283 cx: &mut Context<Self>,
3284 ) {
3285 match event {
3286 remote::RemoteClientEvent::Disconnected => {
3287 self.worktree_store.update(cx, |store, cx| {
3288 store.disconnected_from_host(cx);
3289 });
3290 self.buffer_store.update(cx, |buffer_store, cx| {
3291 buffer_store.disconnected_from_host(cx)
3292 });
3293 self.lsp_store.update(cx, |lsp_store, _cx| {
3294 lsp_store.disconnected_from_ssh_remote()
3295 });
3296 cx.emit(Event::DisconnectedFromSshRemote);
3297 }
3298 }
3299 }
3300
3301 fn on_settings_observer_event(
3302 &mut self,
3303 _: Entity<SettingsObserver>,
3304 event: &SettingsObserverEvent,
3305 cx: &mut Context<Self>,
3306 ) {
3307 match event {
3308 SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
3309 Err(InvalidSettingsError::LocalSettings { message, path }) => {
3310 let message = format!("Failed to set local settings in {path:?}:\n{message}");
3311 cx.emit(Event::Toast {
3312 notification_id: format!("local-settings-{path:?}").into(),
3313 message,
3314 });
3315 }
3316 Ok(path) => cx.emit(Event::HideToast {
3317 notification_id: format!("local-settings-{path:?}").into(),
3318 }),
3319 Err(_) => {}
3320 },
3321 SettingsObserverEvent::LocalTasksUpdated(result) => match result {
3322 Err(InvalidSettingsError::Tasks { message, path }) => {
3323 let message = format!("Failed to set local tasks in {path:?}:\n{message}");
3324 cx.emit(Event::Toast {
3325 notification_id: format!("local-tasks-{path:?}").into(),
3326 message,
3327 });
3328 }
3329 Ok(path) => cx.emit(Event::HideToast {
3330 notification_id: format!("local-tasks-{path:?}").into(),
3331 }),
3332 Err(_) => {}
3333 },
3334 SettingsObserverEvent::LocalDebugScenariosUpdated(result) => match result {
3335 Err(InvalidSettingsError::Debug { message, path }) => {
3336 let message =
3337 format!("Failed to set local debug scenarios in {path:?}:\n{message}");
3338 cx.emit(Event::Toast {
3339 notification_id: format!("local-debug-scenarios-{path:?}").into(),
3340 message,
3341 });
3342 }
3343 Ok(path) => cx.emit(Event::HideToast {
3344 notification_id: format!("local-debug-scenarios-{path:?}").into(),
3345 }),
3346 Err(_) => {}
3347 },
3348 }
3349 }
3350
3351 fn on_worktree_store_event(
3352 &mut self,
3353 _: Entity<WorktreeStore>,
3354 event: &WorktreeStoreEvent,
3355 cx: &mut Context<Self>,
3356 ) {
3357 match event {
3358 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3359 self.on_worktree_added(worktree, cx);
3360 cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
3361 }
3362 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
3363 cx.emit(Event::WorktreeRemoved(*id));
3364 }
3365 WorktreeStoreEvent::WorktreeReleased(_, id) => {
3366 self.on_worktree_released(*id, cx);
3367 }
3368 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
3369 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
3370 WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
3371 self.client()
3372 .telemetry()
3373 .report_discovered_project_type_events(*worktree_id, changes);
3374 cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
3375 }
3376 WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
3377 cx.emit(Event::DeletedEntry(*worktree_id, *id))
3378 }
3379 // Listen to the GitStore instead.
3380 WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
3381 }
3382 }
3383
3384 fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
3385 let mut remotely_created_models = self.remotely_created_models.lock();
3386 if remotely_created_models.retain_count > 0 {
3387 remotely_created_models.worktrees.push(worktree.clone())
3388 }
3389 }
3390
3391 fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3392 if let Some(remote) = &self.remote_client {
3393 remote
3394 .read(cx)
3395 .proto_client()
3396 .send(proto::RemoveWorktree {
3397 worktree_id: id_to_remove.to_proto(),
3398 })
3399 .log_err();
3400 }
3401 }
3402
3403 fn on_buffer_event(
3404 &mut self,
3405 buffer: Entity<Buffer>,
3406 event: &BufferEvent,
3407 cx: &mut Context<Self>,
3408 ) -> Option<()> {
3409 if matches!(event, BufferEvent::Edited | BufferEvent::Reloaded) {
3410 self.request_buffer_diff_recalculation(&buffer, cx);
3411 }
3412
3413 let buffer_id = buffer.read(cx).remote_id();
3414 match event {
3415 BufferEvent::ReloadNeeded => {
3416 if !self.is_via_collab() {
3417 self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
3418 .detach_and_log_err(cx);
3419 }
3420 }
3421 BufferEvent::Operation {
3422 operation,
3423 is_local: true,
3424 } => {
3425 let operation = language::proto::serialize_operation(operation);
3426
3427 if let Some(remote) = &self.remote_client {
3428 remote
3429 .read(cx)
3430 .proto_client()
3431 .send(proto::UpdateBuffer {
3432 project_id: 0,
3433 buffer_id: buffer_id.to_proto(),
3434 operations: vec![operation.clone()],
3435 })
3436 .ok();
3437 }
3438
3439 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
3440 buffer_id,
3441 operation,
3442 })
3443 .ok();
3444 }
3445
3446 _ => {}
3447 }
3448
3449 None
3450 }
3451
3452 fn on_image_event(
3453 &mut self,
3454 image: Entity<ImageItem>,
3455 event: &ImageItemEvent,
3456 cx: &mut Context<Self>,
3457 ) -> Option<()> {
3458 // TODO: handle image events from remote
3459 if let ImageItemEvent::ReloadNeeded = event
3460 && !self.is_via_collab()
3461 {
3462 self.reload_images([image].into_iter().collect(), cx)
3463 .detach_and_log_err(cx);
3464 }
3465
3466 None
3467 }
3468
3469 fn request_buffer_diff_recalculation(
3470 &mut self,
3471 buffer: &Entity<Buffer>,
3472 cx: &mut Context<Self>,
3473 ) {
3474 self.buffers_needing_diff.insert(buffer.downgrade());
3475 let first_insertion = self.buffers_needing_diff.len() == 1;
3476 let settings = ProjectSettings::get_global(cx);
3477 let delay = settings.git.gutter_debounce;
3478
3479 if delay == 0 {
3480 if first_insertion {
3481 let this = cx.weak_entity();
3482 cx.defer(move |cx| {
3483 if let Some(this) = this.upgrade() {
3484 this.update(cx, |this, cx| {
3485 this.recalculate_buffer_diffs(cx).detach();
3486 });
3487 }
3488 });
3489 }
3490 return;
3491 }
3492
3493 const MIN_DELAY: u64 = 50;
3494 let delay = delay.max(MIN_DELAY);
3495 let duration = Duration::from_millis(delay);
3496
3497 self.git_diff_debouncer
3498 .fire_new(duration, cx, move |this, cx| {
3499 this.recalculate_buffer_diffs(cx)
3500 });
3501 }
3502
3503 fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
3504 cx.spawn(async move |this, cx| {
3505 loop {
3506 let task = this
3507 .update(cx, |this, cx| {
3508 let buffers = this
3509 .buffers_needing_diff
3510 .drain()
3511 .filter_map(|buffer| buffer.upgrade())
3512 .collect::<Vec<_>>();
3513 if buffers.is_empty() {
3514 None
3515 } else {
3516 Some(this.git_store.update(cx, |git_store, cx| {
3517 git_store.recalculate_buffer_diffs(buffers, cx)
3518 }))
3519 }
3520 })
3521 .ok()
3522 .flatten();
3523
3524 if let Some(task) = task {
3525 task.await;
3526 } else {
3527 break;
3528 }
3529 }
3530 })
3531 }
3532
3533 pub fn set_language_for_buffer(
3534 &mut self,
3535 buffer: &Entity<Buffer>,
3536 new_language: Arc<Language>,
3537 cx: &mut Context<Self>,
3538 ) {
3539 self.lsp_store.update(cx, |lsp_store, cx| {
3540 lsp_store.set_language_for_buffer(buffer, new_language, cx)
3541 })
3542 }
3543
3544 pub fn restart_language_servers_for_buffers(
3545 &mut self,
3546 buffers: Vec<Entity<Buffer>>,
3547 only_restart_servers: HashSet<LanguageServerSelector>,
3548 cx: &mut Context<Self>,
3549 ) {
3550 self.lsp_store.update(cx, |lsp_store, cx| {
3551 lsp_store.restart_language_servers_for_buffers(buffers, only_restart_servers, cx)
3552 })
3553 }
3554
3555 pub fn stop_language_servers_for_buffers(
3556 &mut self,
3557 buffers: Vec<Entity<Buffer>>,
3558 also_restart_servers: HashSet<LanguageServerSelector>,
3559 cx: &mut Context<Self>,
3560 ) {
3561 self.lsp_store
3562 .update(cx, |lsp_store, cx| {
3563 lsp_store.stop_language_servers_for_buffers(buffers, also_restart_servers, cx)
3564 })
3565 .detach_and_log_err(cx);
3566 }
3567
3568 pub fn cancel_language_server_work_for_buffers(
3569 &mut self,
3570 buffers: impl IntoIterator<Item = Entity<Buffer>>,
3571 cx: &mut Context<Self>,
3572 ) {
3573 self.lsp_store.update(cx, |lsp_store, cx| {
3574 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3575 })
3576 }
3577
3578 pub fn cancel_language_server_work(
3579 &mut self,
3580 server_id: LanguageServerId,
3581 token_to_cancel: Option<ProgressToken>,
3582 cx: &mut Context<Self>,
3583 ) {
3584 self.lsp_store.update(cx, |lsp_store, cx| {
3585 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3586 })
3587 }
3588
3589 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3590 self.buffer_ordered_messages_tx
3591 .unbounded_send(message)
3592 .map_err(|e| anyhow!(e))
3593 }
3594
3595 pub fn available_toolchains(
3596 &self,
3597 path: ProjectPath,
3598 language_name: LanguageName,
3599 cx: &App,
3600 ) -> Task<Option<Toolchains>> {
3601 if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3602 cx.spawn(async move |cx| {
3603 toolchain_store
3604 .update(cx, |this, cx| this.list_toolchains(path, language_name, cx))
3605 .ok()?
3606 .await
3607 })
3608 } else {
3609 Task::ready(None)
3610 }
3611 }
3612
3613 pub async fn toolchain_metadata(
3614 languages: Arc<LanguageRegistry>,
3615 language_name: LanguageName,
3616 ) -> Option<ToolchainMetadata> {
3617 languages
3618 .language_for_name(language_name.as_ref())
3619 .await
3620 .ok()?
3621 .toolchain_lister()
3622 .map(|lister| lister.meta())
3623 }
3624
3625 pub fn add_toolchain(
3626 &self,
3627 toolchain: Toolchain,
3628 scope: ToolchainScope,
3629 cx: &mut Context<Self>,
3630 ) {
3631 maybe!({
3632 self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3633 this.add_toolchain(toolchain, scope, cx);
3634 });
3635 Some(())
3636 });
3637 }
3638
3639 pub fn remove_toolchain(
3640 &self,
3641 toolchain: Toolchain,
3642 scope: ToolchainScope,
3643 cx: &mut Context<Self>,
3644 ) {
3645 maybe!({
3646 self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3647 this.remove_toolchain(toolchain, scope, cx);
3648 });
3649 Some(())
3650 });
3651 }
3652
3653 pub fn user_toolchains(
3654 &self,
3655 cx: &App,
3656 ) -> Option<BTreeMap<ToolchainScope, IndexSet<Toolchain>>> {
3657 Some(self.toolchain_store.as_ref()?.read(cx).user_toolchains())
3658 }
3659
3660 pub fn resolve_toolchain(
3661 &self,
3662 path: PathBuf,
3663 language_name: LanguageName,
3664 cx: &App,
3665 ) -> Task<Result<Toolchain>> {
3666 if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3667 cx.spawn(async move |cx| {
3668 toolchain_store
3669 .update(cx, |this, cx| {
3670 this.resolve_toolchain(path, language_name, cx)
3671 })?
3672 .await
3673 })
3674 } else {
3675 Task::ready(Err(anyhow!("This project does not support toolchains")))
3676 }
3677 }
3678
3679 pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
3680 self.toolchain_store.clone()
3681 }
3682 pub fn activate_toolchain(
3683 &self,
3684 path: ProjectPath,
3685 toolchain: Toolchain,
3686 cx: &mut App,
3687 ) -> Task<Option<()>> {
3688 let Some(toolchain_store) = self.toolchain_store.clone() else {
3689 return Task::ready(None);
3690 };
3691 toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3692 }
3693 pub fn active_toolchain(
3694 &self,
3695 path: ProjectPath,
3696 language_name: LanguageName,
3697 cx: &App,
3698 ) -> Task<Option<Toolchain>> {
3699 let Some(toolchain_store) = self.toolchain_store.clone() else {
3700 return Task::ready(None);
3701 };
3702 toolchain_store
3703 .read(cx)
3704 .active_toolchain(path, language_name, cx)
3705 }
3706 pub fn language_server_statuses<'a>(
3707 &'a self,
3708 cx: &'a App,
3709 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3710 self.lsp_store.read(cx).language_server_statuses()
3711 }
3712
3713 pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3714 self.lsp_store.read(cx).last_formatting_failure()
3715 }
3716
3717 pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3718 self.lsp_store
3719 .update(cx, |store, _| store.reset_last_formatting_failure());
3720 }
3721
3722 pub fn reload_buffers(
3723 &self,
3724 buffers: HashSet<Entity<Buffer>>,
3725 push_to_history: bool,
3726 cx: &mut Context<Self>,
3727 ) -> Task<Result<ProjectTransaction>> {
3728 self.buffer_store.update(cx, |buffer_store, cx| {
3729 buffer_store.reload_buffers(buffers, push_to_history, cx)
3730 })
3731 }
3732
3733 pub fn reload_images(
3734 &self,
3735 images: HashSet<Entity<ImageItem>>,
3736 cx: &mut Context<Self>,
3737 ) -> Task<Result<()>> {
3738 self.image_store
3739 .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3740 }
3741
3742 pub fn format(
3743 &mut self,
3744 buffers: HashSet<Entity<Buffer>>,
3745 target: LspFormatTarget,
3746 push_to_history: bool,
3747 trigger: lsp_store::FormatTrigger,
3748 cx: &mut Context<Project>,
3749 ) -> Task<anyhow::Result<ProjectTransaction>> {
3750 self.lsp_store.update(cx, |lsp_store, cx| {
3751 lsp_store.format(buffers, target, push_to_history, trigger, cx)
3752 })
3753 }
3754
3755 pub fn definitions<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.definitions(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 declarations<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.declarations(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 type_definitions<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.type_definitions(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 implementations<T: ToPointUtf16>(
3810 &mut self,
3811 buffer: &Entity<Buffer>,
3812 position: T,
3813 cx: &mut Context<Self>,
3814 ) -> Task<Result<Option<Vec<LocationLink>>>> {
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.implementations(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 references<T: ToPointUtf16>(
3828 &mut self,
3829 buffer: &Entity<Buffer>,
3830 position: T,
3831 cx: &mut Context<Self>,
3832 ) -> Task<Result<Option<Vec<Location>>>> {
3833 let position = position.to_point_utf16(buffer.read(cx));
3834 let guard = self.retain_remotely_created_models(cx);
3835 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3836 lsp_store.references(buffer, position, cx)
3837 });
3838 cx.background_spawn(async move {
3839 let result = task.await;
3840 drop(guard);
3841 result
3842 })
3843 }
3844
3845 pub fn document_highlights<T: ToPointUtf16>(
3846 &mut self,
3847 buffer: &Entity<Buffer>,
3848 position: T,
3849 cx: &mut Context<Self>,
3850 ) -> Task<Result<Vec<DocumentHighlight>>> {
3851 let position = position.to_point_utf16(buffer.read(cx));
3852 self.request_lsp(
3853 buffer.clone(),
3854 LanguageServerToQuery::FirstCapable,
3855 GetDocumentHighlights { position },
3856 cx,
3857 )
3858 }
3859
3860 pub fn document_symbols(
3861 &mut self,
3862 buffer: &Entity<Buffer>,
3863 cx: &mut Context<Self>,
3864 ) -> Task<Result<Vec<DocumentSymbol>>> {
3865 self.request_lsp(
3866 buffer.clone(),
3867 LanguageServerToQuery::FirstCapable,
3868 GetDocumentSymbols,
3869 cx,
3870 )
3871 }
3872
3873 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3874 self.lsp_store
3875 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3876 }
3877
3878 pub fn open_buffer_for_symbol(
3879 &mut self,
3880 symbol: &Symbol,
3881 cx: &mut Context<Self>,
3882 ) -> Task<Result<Entity<Buffer>>> {
3883 self.lsp_store.update(cx, |lsp_store, cx| {
3884 lsp_store.open_buffer_for_symbol(symbol, cx)
3885 })
3886 }
3887
3888 pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3889 let guard = self.retain_remotely_created_models(cx);
3890 let Some(remote) = self.remote_client.as_ref() else {
3891 return Task::ready(Err(anyhow!("not an ssh project")));
3892 };
3893
3894 let proto_client = remote.read(cx).proto_client();
3895
3896 cx.spawn(async move |project, cx| {
3897 let buffer = proto_client
3898 .request(proto::OpenServerSettings {
3899 project_id: REMOTE_SERVER_PROJECT_ID,
3900 })
3901 .await?;
3902
3903 let buffer = project
3904 .update(cx, |project, cx| {
3905 project.buffer_store.update(cx, |buffer_store, cx| {
3906 anyhow::Ok(
3907 buffer_store
3908 .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3909 )
3910 })
3911 })??
3912 .await;
3913
3914 drop(guard);
3915 buffer
3916 })
3917 }
3918
3919 pub fn open_local_buffer_via_lsp(
3920 &mut self,
3921 abs_path: lsp::Uri,
3922 language_server_id: LanguageServerId,
3923 cx: &mut Context<Self>,
3924 ) -> Task<Result<Entity<Buffer>>> {
3925 self.lsp_store.update(cx, |lsp_store, cx| {
3926 lsp_store.open_local_buffer_via_lsp(abs_path, language_server_id, cx)
3927 })
3928 }
3929
3930 pub fn hover<T: ToPointUtf16>(
3931 &self,
3932 buffer: &Entity<Buffer>,
3933 position: T,
3934 cx: &mut Context<Self>,
3935 ) -> Task<Option<Vec<Hover>>> {
3936 let position = position.to_point_utf16(buffer.read(cx));
3937 self.lsp_store
3938 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3939 }
3940
3941 pub fn linked_edits(
3942 &self,
3943 buffer: &Entity<Buffer>,
3944 position: Anchor,
3945 cx: &mut Context<Self>,
3946 ) -> Task<Result<Vec<Range<Anchor>>>> {
3947 self.lsp_store.update(cx, |lsp_store, cx| {
3948 lsp_store.linked_edits(buffer, position, cx)
3949 })
3950 }
3951
3952 pub fn completions<T: ToOffset + ToPointUtf16>(
3953 &self,
3954 buffer: &Entity<Buffer>,
3955 position: T,
3956 context: CompletionContext,
3957 cx: &mut Context<Self>,
3958 ) -> Task<Result<Vec<CompletionResponse>>> {
3959 let position = position.to_point_utf16(buffer.read(cx));
3960 self.lsp_store.update(cx, |lsp_store, cx| {
3961 lsp_store.completions(buffer, position, context, cx)
3962 })
3963 }
3964
3965 pub fn code_actions<T: Clone + ToOffset>(
3966 &mut self,
3967 buffer_handle: &Entity<Buffer>,
3968 range: Range<T>,
3969 kinds: Option<Vec<CodeActionKind>>,
3970 cx: &mut Context<Self>,
3971 ) -> Task<Result<Option<Vec<CodeAction>>>> {
3972 let buffer = buffer_handle.read(cx);
3973 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3974 self.lsp_store.update(cx, |lsp_store, cx| {
3975 lsp_store.code_actions(buffer_handle, range, kinds, cx)
3976 })
3977 }
3978
3979 pub fn code_lens_actions<T: Clone + ToOffset>(
3980 &mut self,
3981 buffer: &Entity<Buffer>,
3982 range: Range<T>,
3983 cx: &mut Context<Self>,
3984 ) -> Task<Result<Option<Vec<CodeAction>>>> {
3985 let snapshot = buffer.read(cx).snapshot();
3986 let range = range.to_point(&snapshot);
3987 let range_start = snapshot.anchor_before(range.start);
3988 let range_end = if range.start == range.end {
3989 range_start
3990 } else {
3991 snapshot.anchor_after(range.end)
3992 };
3993 let range = range_start..range_end;
3994 let code_lens_actions = self
3995 .lsp_store
3996 .update(cx, |lsp_store, cx| lsp_store.code_lens_actions(buffer, cx));
3997
3998 cx.background_spawn(async move {
3999 let mut code_lens_actions = code_lens_actions
4000 .await
4001 .map_err(|e| anyhow!("code lens fetch failed: {e:#}"))?;
4002 if let Some(code_lens_actions) = &mut code_lens_actions {
4003 code_lens_actions.retain(|code_lens_action| {
4004 range
4005 .start
4006 .cmp(&code_lens_action.range.start, &snapshot)
4007 .is_ge()
4008 && range
4009 .end
4010 .cmp(&code_lens_action.range.end, &snapshot)
4011 .is_le()
4012 });
4013 }
4014 Ok(code_lens_actions)
4015 })
4016 }
4017
4018 pub fn apply_code_action(
4019 &self,
4020 buffer_handle: Entity<Buffer>,
4021 action: CodeAction,
4022 push_to_history: bool,
4023 cx: &mut Context<Self>,
4024 ) -> Task<Result<ProjectTransaction>> {
4025 self.lsp_store.update(cx, |lsp_store, cx| {
4026 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
4027 })
4028 }
4029
4030 pub fn apply_code_action_kind(
4031 &self,
4032 buffers: HashSet<Entity<Buffer>>,
4033 kind: CodeActionKind,
4034 push_to_history: bool,
4035 cx: &mut Context<Self>,
4036 ) -> Task<Result<ProjectTransaction>> {
4037 self.lsp_store.update(cx, |lsp_store, cx| {
4038 lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
4039 })
4040 }
4041
4042 pub fn prepare_rename<T: ToPointUtf16>(
4043 &mut self,
4044 buffer: Entity<Buffer>,
4045 position: T,
4046 cx: &mut Context<Self>,
4047 ) -> Task<Result<PrepareRenameResponse>> {
4048 let position = position.to_point_utf16(buffer.read(cx));
4049 self.request_lsp(
4050 buffer,
4051 LanguageServerToQuery::FirstCapable,
4052 PrepareRename { position },
4053 cx,
4054 )
4055 }
4056
4057 pub fn perform_rename<T: ToPointUtf16>(
4058 &mut self,
4059 buffer: Entity<Buffer>,
4060 position: T,
4061 new_name: String,
4062 cx: &mut Context<Self>,
4063 ) -> Task<Result<ProjectTransaction>> {
4064 let push_to_history = true;
4065 let position = position.to_point_utf16(buffer.read(cx));
4066 self.request_lsp(
4067 buffer,
4068 LanguageServerToQuery::FirstCapable,
4069 PerformRename {
4070 position,
4071 new_name,
4072 push_to_history,
4073 },
4074 cx,
4075 )
4076 }
4077
4078 pub fn on_type_format<T: ToPointUtf16>(
4079 &mut self,
4080 buffer: Entity<Buffer>,
4081 position: T,
4082 trigger: String,
4083 push_to_history: bool,
4084 cx: &mut Context<Self>,
4085 ) -> Task<Result<Option<Transaction>>> {
4086 self.lsp_store.update(cx, |lsp_store, cx| {
4087 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
4088 })
4089 }
4090
4091 pub fn inline_values(
4092 &mut self,
4093 session: Entity<Session>,
4094 active_stack_frame: ActiveStackFrame,
4095 buffer_handle: Entity<Buffer>,
4096 range: Range<text::Anchor>,
4097 cx: &mut Context<Self>,
4098 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
4099 let snapshot = buffer_handle.read(cx).snapshot();
4100
4101 let captures =
4102 snapshot.debug_variables_query(Anchor::min_for_buffer(snapshot.remote_id())..range.end);
4103
4104 let row = snapshot
4105 .summary_for_anchor::<text::PointUtf16>(&range.end)
4106 .row as usize;
4107
4108 let inline_value_locations = provide_inline_values(captures, &snapshot, row);
4109
4110 let stack_frame_id = active_stack_frame.stack_frame_id;
4111 cx.spawn(async move |this, cx| {
4112 this.update(cx, |project, cx| {
4113 project.dap_store().update(cx, |dap_store, cx| {
4114 dap_store.resolve_inline_value_locations(
4115 session,
4116 stack_frame_id,
4117 buffer_handle,
4118 inline_value_locations,
4119 cx,
4120 )
4121 })
4122 })?
4123 .await
4124 })
4125 }
4126
4127 fn search_impl(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> SearchResultsHandle {
4128 let client: Option<(AnyProtoClient, _)> = if let Some(ssh_client) = &self.remote_client {
4129 Some((ssh_client.read(cx).proto_client(), 0))
4130 } else if let Some(remote_id) = self.remote_id() {
4131 self.is_local()
4132 .not()
4133 .then(|| (self.collab_client.clone().into(), remote_id))
4134 } else {
4135 None
4136 };
4137 let searcher = if query.is_opened_only() {
4138 project_search::Search::open_buffers_only(
4139 self.buffer_store.clone(),
4140 self.worktree_store.clone(),
4141 project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4142 )
4143 } else {
4144 match client {
4145 Some((client, remote_id)) => project_search::Search::remote(
4146 self.buffer_store.clone(),
4147 self.worktree_store.clone(),
4148 project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4149 (client, remote_id, self.remotely_created_models.clone()),
4150 ),
4151 None => project_search::Search::local(
4152 self.fs.clone(),
4153 self.buffer_store.clone(),
4154 self.worktree_store.clone(),
4155 project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4156 cx,
4157 ),
4158 }
4159 };
4160 searcher.into_handle(query, cx)
4161 }
4162
4163 pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
4164 self.search_impl(query, cx).results(cx)
4165 }
4166
4167 pub fn request_lsp<R: LspCommand>(
4168 &mut self,
4169 buffer_handle: Entity<Buffer>,
4170 server: LanguageServerToQuery,
4171 request: R,
4172 cx: &mut Context<Self>,
4173 ) -> Task<Result<R::Response>>
4174 where
4175 <R::LspRequest as lsp::request::Request>::Result: Send,
4176 <R::LspRequest as lsp::request::Request>::Params: Send,
4177 {
4178 let guard = self.retain_remotely_created_models(cx);
4179 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4180 lsp_store.request_lsp(buffer_handle, server, request, cx)
4181 });
4182 cx.background_spawn(async move {
4183 let result = task.await;
4184 drop(guard);
4185 result
4186 })
4187 }
4188
4189 /// Move a worktree to a new position in the worktree order.
4190 ///
4191 /// The worktree will moved to the opposite side of the destination worktree.
4192 ///
4193 /// # Example
4194 ///
4195 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4196 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4197 ///
4198 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4199 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4200 ///
4201 /// # Errors
4202 ///
4203 /// An error will be returned if the worktree or destination worktree are not found.
4204 pub fn move_worktree(
4205 &mut self,
4206 source: WorktreeId,
4207 destination: WorktreeId,
4208 cx: &mut Context<Self>,
4209 ) -> Result<()> {
4210 self.worktree_store.update(cx, |worktree_store, cx| {
4211 worktree_store.move_worktree(source, destination, cx)
4212 })
4213 }
4214
4215 pub fn find_or_create_worktree(
4216 &mut self,
4217 abs_path: impl AsRef<Path>,
4218 visible: bool,
4219 cx: &mut Context<Self>,
4220 ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
4221 self.worktree_store.update(cx, |worktree_store, cx| {
4222 worktree_store.find_or_create_worktree(abs_path, visible, cx)
4223 })
4224 }
4225
4226 pub fn find_worktree(
4227 &self,
4228 abs_path: &Path,
4229 cx: &App,
4230 ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
4231 self.worktree_store.read(cx).find_worktree(abs_path, cx)
4232 }
4233
4234 pub fn is_shared(&self) -> bool {
4235 match &self.client_state {
4236 ProjectClientState::Shared { .. } => true,
4237 ProjectClientState::Local => false,
4238 ProjectClientState::Remote { .. } => true,
4239 }
4240 }
4241
4242 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4243 pub fn resolve_path_in_buffer(
4244 &self,
4245 path: &str,
4246 buffer: &Entity<Buffer>,
4247 cx: &mut Context<Self>,
4248 ) -> Task<Option<ResolvedPath>> {
4249 if util::paths::is_absolute(path, self.path_style(cx)) || path.starts_with("~") {
4250 self.resolve_abs_path(path, cx)
4251 } else {
4252 self.resolve_path_in_worktrees(path, buffer, cx)
4253 }
4254 }
4255
4256 pub fn resolve_abs_file_path(
4257 &self,
4258 path: &str,
4259 cx: &mut Context<Self>,
4260 ) -> Task<Option<ResolvedPath>> {
4261 let resolve_task = self.resolve_abs_path(path, cx);
4262 cx.background_spawn(async move {
4263 let resolved_path = resolve_task.await;
4264 resolved_path.filter(|path| path.is_file())
4265 })
4266 }
4267
4268 pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4269 if self.is_local() {
4270 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4271 let fs = self.fs.clone();
4272 cx.background_spawn(async move {
4273 let metadata = fs.metadata(&expanded).await.ok().flatten();
4274
4275 metadata.map(|metadata| ResolvedPath::AbsPath {
4276 path: expanded.to_string_lossy().into_owned(),
4277 is_dir: metadata.is_dir,
4278 })
4279 })
4280 } else if let Some(ssh_client) = self.remote_client.as_ref() {
4281 let request = ssh_client
4282 .read(cx)
4283 .proto_client()
4284 .request(proto::GetPathMetadata {
4285 project_id: REMOTE_SERVER_PROJECT_ID,
4286 path: path.into(),
4287 });
4288 cx.background_spawn(async move {
4289 let response = request.await.log_err()?;
4290 if response.exists {
4291 Some(ResolvedPath::AbsPath {
4292 path: response.path,
4293 is_dir: response.is_dir,
4294 })
4295 } else {
4296 None
4297 }
4298 })
4299 } else {
4300 Task::ready(None)
4301 }
4302 }
4303
4304 fn resolve_path_in_worktrees(
4305 &self,
4306 path: &str,
4307 buffer: &Entity<Buffer>,
4308 cx: &mut Context<Self>,
4309 ) -> Task<Option<ResolvedPath>> {
4310 let mut candidates = vec![];
4311 let path_style = self.path_style(cx);
4312 if let Ok(path) = RelPath::new(path.as_ref(), path_style) {
4313 candidates.push(path.into_arc());
4314 }
4315
4316 if let Some(file) = buffer.read(cx).file()
4317 && let Some(dir) = file.path().parent()
4318 {
4319 if let Some(joined) = path_style.join(&*dir.display(path_style), path)
4320 && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
4321 {
4322 candidates.push(joined.into_arc());
4323 }
4324 }
4325
4326 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4327 let worktrees_with_ids: Vec<_> = self
4328 .worktrees(cx)
4329 .map(|worktree| {
4330 let id = worktree.read(cx).id();
4331 (worktree, id)
4332 })
4333 .collect();
4334
4335 cx.spawn(async move |_, cx| {
4336 if let Some(buffer_worktree_id) = buffer_worktree_id
4337 && let Some((worktree, _)) = worktrees_with_ids
4338 .iter()
4339 .find(|(_, id)| *id == buffer_worktree_id)
4340 {
4341 for candidate in candidates.iter() {
4342 if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4343 return Some(path);
4344 }
4345 }
4346 }
4347 for (worktree, id) in worktrees_with_ids {
4348 if Some(id) == buffer_worktree_id {
4349 continue;
4350 }
4351 for candidate in candidates.iter() {
4352 if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4353 return Some(path);
4354 }
4355 }
4356 }
4357 None
4358 })
4359 }
4360
4361 fn resolve_path_in_worktree(
4362 worktree: &Entity<Worktree>,
4363 path: &RelPath,
4364 cx: &mut AsyncApp,
4365 ) -> Option<ResolvedPath> {
4366 worktree
4367 .read_with(cx, |worktree, _| {
4368 worktree.entry_for_path(path).map(|entry| {
4369 let project_path = ProjectPath {
4370 worktree_id: worktree.id(),
4371 path: entry.path.clone(),
4372 };
4373 ResolvedPath::ProjectPath {
4374 project_path,
4375 is_dir: entry.is_dir(),
4376 }
4377 })
4378 })
4379 .ok()?
4380 }
4381
4382 pub fn list_directory(
4383 &self,
4384 query: String,
4385 cx: &mut Context<Self>,
4386 ) -> Task<Result<Vec<DirectoryItem>>> {
4387 if self.is_local() {
4388 DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4389 } else if let Some(session) = self.remote_client.as_ref() {
4390 let request = proto::ListRemoteDirectory {
4391 dev_server_id: REMOTE_SERVER_PROJECT_ID,
4392 path: query,
4393 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4394 };
4395
4396 let response = session.read(cx).proto_client().request(request);
4397 cx.background_spawn(async move {
4398 let proto::ListRemoteDirectoryResponse {
4399 entries,
4400 entry_info,
4401 } = response.await?;
4402 Ok(entries
4403 .into_iter()
4404 .zip(entry_info)
4405 .map(|(entry, info)| DirectoryItem {
4406 path: PathBuf::from(entry),
4407 is_dir: info.is_dir,
4408 })
4409 .collect())
4410 })
4411 } else {
4412 Task::ready(Err(anyhow!("cannot list directory in remote project")))
4413 }
4414 }
4415
4416 pub fn create_worktree(
4417 &mut self,
4418 abs_path: impl AsRef<Path>,
4419 visible: bool,
4420 cx: &mut Context<Self>,
4421 ) -> Task<Result<Entity<Worktree>>> {
4422 self.worktree_store.update(cx, |worktree_store, cx| {
4423 worktree_store.create_worktree(abs_path, visible, cx)
4424 })
4425 }
4426
4427 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4428 self.worktree_store.update(cx, |worktree_store, cx| {
4429 worktree_store.remove_worktree(id_to_remove, cx);
4430 });
4431 }
4432
4433 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4434 self.worktree_store.update(cx, |worktree_store, cx| {
4435 worktree_store.add(worktree, cx);
4436 });
4437 }
4438
4439 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4440 let new_active_entry = entry.and_then(|project_path| {
4441 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4442 let entry = worktree.read(cx).entry_for_path(&project_path.path)?;
4443 Some(entry.id)
4444 });
4445 if new_active_entry != self.active_entry {
4446 self.active_entry = new_active_entry;
4447 self.lsp_store.update(cx, |lsp_store, _| {
4448 lsp_store.set_active_entry(new_active_entry);
4449 });
4450 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4451 }
4452 }
4453
4454 pub fn language_servers_running_disk_based_diagnostics<'a>(
4455 &'a self,
4456 cx: &'a App,
4457 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4458 self.lsp_store
4459 .read(cx)
4460 .language_servers_running_disk_based_diagnostics()
4461 }
4462
4463 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4464 self.lsp_store
4465 .read(cx)
4466 .diagnostic_summary(include_ignored, cx)
4467 }
4468
4469 /// Returns a summary of the diagnostics for the provided project path only.
4470 pub fn diagnostic_summary_for_path(&self, path: &ProjectPath, cx: &App) -> DiagnosticSummary {
4471 self.lsp_store
4472 .read(cx)
4473 .diagnostic_summary_for_path(path, cx)
4474 }
4475
4476 pub fn diagnostic_summaries<'a>(
4477 &'a self,
4478 include_ignored: bool,
4479 cx: &'a App,
4480 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4481 self.lsp_store
4482 .read(cx)
4483 .diagnostic_summaries(include_ignored, cx)
4484 }
4485
4486 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4487 self.active_entry
4488 }
4489
4490 pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
4491 self.worktree_store.read(cx).entry_for_path(path, cx)
4492 }
4493
4494 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4495 let worktree = self.worktree_for_entry(entry_id, cx)?;
4496 let worktree = worktree.read(cx);
4497 let worktree_id = worktree.id();
4498 let path = worktree.entry_for_id(entry_id)?.path.clone();
4499 Some(ProjectPath { worktree_id, path })
4500 }
4501
4502 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4503 Some(
4504 self.worktree_for_id(project_path.worktree_id, cx)?
4505 .read(cx)
4506 .absolutize(&project_path.path),
4507 )
4508 }
4509
4510 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4511 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4512 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4513 /// the first visible worktree that has an entry for that relative path.
4514 ///
4515 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4516 /// root name from paths.
4517 ///
4518 /// # Arguments
4519 ///
4520 /// * `path` - An absolute path, or a full path that starts with a worktree root name, or a
4521 /// relative path within a visible worktree.
4522 /// * `cx` - A reference to the `AppContext`.
4523 ///
4524 /// # Returns
4525 ///
4526 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4527 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4528 let path_style = self.path_style(cx);
4529 let path = path.as_ref();
4530 let worktree_store = self.worktree_store.read(cx);
4531
4532 if is_absolute(&path.to_string_lossy(), path_style) {
4533 for worktree in worktree_store.visible_worktrees(cx) {
4534 let worktree_abs_path = worktree.read(cx).abs_path();
4535
4536 if let Ok(relative_path) = path.strip_prefix(worktree_abs_path)
4537 && let Ok(path) = RelPath::new(relative_path, path_style)
4538 {
4539 return Some(ProjectPath {
4540 worktree_id: worktree.read(cx).id(),
4541 path: path.into_arc(),
4542 });
4543 }
4544 }
4545 } else {
4546 for worktree in worktree_store.visible_worktrees(cx) {
4547 let worktree_root_name = worktree.read(cx).root_name();
4548 if let Ok(relative_path) = path.strip_prefix(worktree_root_name.as_std_path())
4549 && let Ok(path) = RelPath::new(relative_path, path_style)
4550 {
4551 return Some(ProjectPath {
4552 worktree_id: worktree.read(cx).id(),
4553 path: path.into_arc(),
4554 });
4555 }
4556 }
4557
4558 for worktree in worktree_store.visible_worktrees(cx) {
4559 let worktree = worktree.read(cx);
4560 if let Ok(path) = RelPath::new(path, path_style)
4561 && let Some(entry) = worktree.entry_for_path(&path)
4562 {
4563 return Some(ProjectPath {
4564 worktree_id: worktree.id(),
4565 path: entry.path.clone(),
4566 });
4567 }
4568 }
4569 }
4570
4571 None
4572 }
4573
4574 /// If there's only one visible worktree, returns the given worktree-relative path with no prefix.
4575 ///
4576 /// Otherwise, returns the full path for the project path (obtained by prefixing the worktree-relative path with the name of the worktree).
4577 pub fn short_full_path_for_project_path(
4578 &self,
4579 project_path: &ProjectPath,
4580 cx: &App,
4581 ) -> Option<String> {
4582 let path_style = self.path_style(cx);
4583 if self.visible_worktrees(cx).take(2).count() < 2 {
4584 return Some(project_path.path.display(path_style).to_string());
4585 }
4586 self.worktree_for_id(project_path.worktree_id, cx)
4587 .map(|worktree| {
4588 let worktree_name = worktree.read(cx).root_name();
4589 worktree_name
4590 .join(&project_path.path)
4591 .display(path_style)
4592 .to_string()
4593 })
4594 }
4595
4596 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4597 self.worktree_store
4598 .read(cx)
4599 .project_path_for_absolute_path(abs_path, cx)
4600 }
4601
4602 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4603 Some(
4604 self.worktree_for_id(project_path.worktree_id, cx)?
4605 .read(cx)
4606 .abs_path()
4607 .to_path_buf(),
4608 )
4609 }
4610
4611 pub fn blame_buffer(
4612 &self,
4613 buffer: &Entity<Buffer>,
4614 version: Option<clock::Global>,
4615 cx: &mut App,
4616 ) -> Task<Result<Option<Blame>>> {
4617 self.git_store.update(cx, |git_store, cx| {
4618 git_store.blame_buffer(buffer, version, cx)
4619 })
4620 }
4621
4622 pub fn get_permalink_to_line(
4623 &self,
4624 buffer: &Entity<Buffer>,
4625 selection: Range<u32>,
4626 cx: &mut App,
4627 ) -> Task<Result<url::Url>> {
4628 self.git_store.update(cx, |git_store, cx| {
4629 git_store.get_permalink_to_line(buffer, selection, cx)
4630 })
4631 }
4632
4633 // RPC message handlers
4634
4635 async fn handle_unshare_project(
4636 this: Entity<Self>,
4637 _: TypedEnvelope<proto::UnshareProject>,
4638 mut cx: AsyncApp,
4639 ) -> Result<()> {
4640 this.update(&mut cx, |this, cx| {
4641 if this.is_local() || this.is_via_remote_server() {
4642 this.unshare(cx)?;
4643 } else {
4644 this.disconnected_from_host(cx);
4645 }
4646 Ok(())
4647 })?
4648 }
4649
4650 async fn handle_add_collaborator(
4651 this: Entity<Self>,
4652 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4653 mut cx: AsyncApp,
4654 ) -> Result<()> {
4655 let collaborator = envelope
4656 .payload
4657 .collaborator
4658 .take()
4659 .context("empty collaborator")?;
4660
4661 let collaborator = Collaborator::from_proto(collaborator)?;
4662 this.update(&mut cx, |this, cx| {
4663 this.buffer_store.update(cx, |buffer_store, _| {
4664 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4665 });
4666 this.breakpoint_store.read(cx).broadcast();
4667 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4668 this.collaborators
4669 .insert(collaborator.peer_id, collaborator);
4670 })?;
4671
4672 Ok(())
4673 }
4674
4675 async fn handle_update_project_collaborator(
4676 this: Entity<Self>,
4677 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4678 mut cx: AsyncApp,
4679 ) -> Result<()> {
4680 let old_peer_id = envelope
4681 .payload
4682 .old_peer_id
4683 .context("missing old peer id")?;
4684 let new_peer_id = envelope
4685 .payload
4686 .new_peer_id
4687 .context("missing new peer id")?;
4688 this.update(&mut cx, |this, cx| {
4689 let collaborator = this
4690 .collaborators
4691 .remove(&old_peer_id)
4692 .context("received UpdateProjectCollaborator for unknown peer")?;
4693 let is_host = collaborator.is_host;
4694 this.collaborators.insert(new_peer_id, collaborator);
4695
4696 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4697 this.buffer_store.update(cx, |buffer_store, _| {
4698 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4699 });
4700
4701 if is_host {
4702 this.buffer_store
4703 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4704 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4705 .unwrap();
4706 cx.emit(Event::HostReshared);
4707 }
4708
4709 cx.emit(Event::CollaboratorUpdated {
4710 old_peer_id,
4711 new_peer_id,
4712 });
4713 Ok(())
4714 })?
4715 }
4716
4717 async fn handle_remove_collaborator(
4718 this: Entity<Self>,
4719 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4720 mut cx: AsyncApp,
4721 ) -> Result<()> {
4722 this.update(&mut cx, |this, cx| {
4723 let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4724 let replica_id = this
4725 .collaborators
4726 .remove(&peer_id)
4727 .with_context(|| format!("unknown peer {peer_id:?}"))?
4728 .replica_id;
4729 this.buffer_store.update(cx, |buffer_store, cx| {
4730 buffer_store.forget_shared_buffers_for(&peer_id);
4731 for buffer in buffer_store.buffers() {
4732 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4733 }
4734 });
4735 this.git_store.update(cx, |git_store, _| {
4736 git_store.forget_shared_diffs_for(&peer_id);
4737 });
4738
4739 cx.emit(Event::CollaboratorLeft(peer_id));
4740 Ok(())
4741 })?
4742 }
4743
4744 async fn handle_update_project(
4745 this: Entity<Self>,
4746 envelope: TypedEnvelope<proto::UpdateProject>,
4747 mut cx: AsyncApp,
4748 ) -> Result<()> {
4749 this.update(&mut cx, |this, cx| {
4750 // Don't handle messages that were sent before the response to us joining the project
4751 if envelope.message_id > this.join_project_response_message_id {
4752 cx.update_global::<SettingsStore, _>(|store, cx| {
4753 for worktree_metadata in &envelope.payload.worktrees {
4754 store
4755 .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
4756 .log_err();
4757 }
4758 });
4759
4760 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4761 }
4762 Ok(())
4763 })?
4764 }
4765
4766 async fn handle_toast(
4767 this: Entity<Self>,
4768 envelope: TypedEnvelope<proto::Toast>,
4769 mut cx: AsyncApp,
4770 ) -> Result<()> {
4771 this.update(&mut cx, |_, cx| {
4772 cx.emit(Event::Toast {
4773 notification_id: envelope.payload.notification_id.into(),
4774 message: envelope.payload.message,
4775 });
4776 Ok(())
4777 })?
4778 }
4779
4780 async fn handle_language_server_prompt_request(
4781 this: Entity<Self>,
4782 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4783 mut cx: AsyncApp,
4784 ) -> Result<proto::LanguageServerPromptResponse> {
4785 let (tx, rx) = smol::channel::bounded(1);
4786 let actions: Vec<_> = envelope
4787 .payload
4788 .actions
4789 .into_iter()
4790 .map(|action| MessageActionItem {
4791 title: action,
4792 properties: Default::default(),
4793 })
4794 .collect();
4795 this.update(&mut cx, |_, cx| {
4796 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4797 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4798 message: envelope.payload.message,
4799 actions: actions.clone(),
4800 lsp_name: envelope.payload.lsp_name,
4801 response_channel: tx,
4802 }));
4803
4804 anyhow::Ok(())
4805 })??;
4806
4807 // We drop `this` to avoid holding a reference in this future for too
4808 // long.
4809 // If we keep the reference, we might not drop the `Project` early
4810 // enough when closing a window and it will only get releases on the
4811 // next `flush_effects()` call.
4812 drop(this);
4813
4814 let mut rx = pin!(rx);
4815 let answer = rx.next().await;
4816
4817 Ok(LanguageServerPromptResponse {
4818 action_response: answer.and_then(|answer| {
4819 actions
4820 .iter()
4821 .position(|action| *action == answer)
4822 .map(|index| index as u64)
4823 }),
4824 })
4825 }
4826
4827 async fn handle_hide_toast(
4828 this: Entity<Self>,
4829 envelope: TypedEnvelope<proto::HideToast>,
4830 mut cx: AsyncApp,
4831 ) -> Result<()> {
4832 this.update(&mut cx, |_, cx| {
4833 cx.emit(Event::HideToast {
4834 notification_id: envelope.payload.notification_id.into(),
4835 });
4836 Ok(())
4837 })?
4838 }
4839
4840 // Collab sends UpdateWorktree protos as messages
4841 async fn handle_update_worktree(
4842 this: Entity<Self>,
4843 envelope: TypedEnvelope<proto::UpdateWorktree>,
4844 mut cx: AsyncApp,
4845 ) -> Result<()> {
4846 this.update(&mut cx, |project, cx| {
4847 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4848 if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
4849 trusted_worktrees.update(cx, |trusted_worktrees, cx| {
4850 trusted_worktrees.can_trust(worktree_id, cx)
4851 });
4852 }
4853 if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
4854 worktree.update(cx, |worktree, _| {
4855 let worktree = worktree.as_remote_mut().unwrap();
4856 worktree.update_from_remote(envelope.payload);
4857 });
4858 }
4859 Ok(())
4860 })?
4861 }
4862
4863 async fn handle_update_buffer_from_remote_server(
4864 this: Entity<Self>,
4865 envelope: TypedEnvelope<proto::UpdateBuffer>,
4866 cx: AsyncApp,
4867 ) -> Result<proto::Ack> {
4868 let buffer_store = this.read_with(&cx, |this, cx| {
4869 if let Some(remote_id) = this.remote_id() {
4870 let mut payload = envelope.payload.clone();
4871 payload.project_id = remote_id;
4872 cx.background_spawn(this.collab_client.request(payload))
4873 .detach_and_log_err(cx);
4874 }
4875 this.buffer_store.clone()
4876 })?;
4877 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4878 }
4879
4880 async fn handle_trust_worktrees(
4881 this: Entity<Self>,
4882 envelope: TypedEnvelope<proto::TrustWorktrees>,
4883 mut cx: AsyncApp,
4884 ) -> Result<proto::Ack> {
4885 let trusted_worktrees = cx
4886 .update(|cx| TrustedWorktrees::try_get_global(cx))?
4887 .context("missing trusted worktrees")?;
4888 trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
4889 let remote_host = this
4890 .read(cx)
4891 .remote_connection_options(cx)
4892 .map(RemoteHostLocation::from);
4893 trusted_worktrees.trust(
4894 envelope
4895 .payload
4896 .trusted_paths
4897 .into_iter()
4898 .filter_map(|proto_path| PathTrust::from_proto(proto_path))
4899 .collect(),
4900 remote_host,
4901 cx,
4902 );
4903 })?;
4904 Ok(proto::Ack {})
4905 }
4906
4907 async fn handle_restrict_worktrees(
4908 this: Entity<Self>,
4909 envelope: TypedEnvelope<proto::RestrictWorktrees>,
4910 mut cx: AsyncApp,
4911 ) -> Result<proto::Ack> {
4912 let trusted_worktrees = cx
4913 .update(|cx| TrustedWorktrees::try_get_global(cx))?
4914 .context("missing trusted worktrees")?;
4915 trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
4916 let restricted_paths = envelope
4917 .payload
4918 .worktree_ids
4919 .into_iter()
4920 .map(WorktreeId::from_proto)
4921 .map(PathTrust::Worktree)
4922 .collect::<HashSet<_>>();
4923 let remote_host = this
4924 .read(cx)
4925 .remote_connection_options(cx)
4926 .map(RemoteHostLocation::from);
4927 trusted_worktrees.restrict(restricted_paths, remote_host, cx);
4928 })?;
4929 Ok(proto::Ack {})
4930 }
4931
4932 async fn handle_update_buffer(
4933 this: Entity<Self>,
4934 envelope: TypedEnvelope<proto::UpdateBuffer>,
4935 cx: AsyncApp,
4936 ) -> Result<proto::Ack> {
4937 let buffer_store = this.read_with(&cx, |this, cx| {
4938 if let Some(ssh) = &this.remote_client {
4939 let mut payload = envelope.payload.clone();
4940 payload.project_id = REMOTE_SERVER_PROJECT_ID;
4941 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4942 .detach_and_log_err(cx);
4943 }
4944 this.buffer_store.clone()
4945 })?;
4946 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4947 }
4948
4949 fn retain_remotely_created_models(
4950 &mut self,
4951 cx: &mut Context<Self>,
4952 ) -> RemotelyCreatedModelGuard {
4953 Self::retain_remotely_created_models_impl(
4954 &self.remotely_created_models,
4955 &self.buffer_store,
4956 &self.worktree_store,
4957 cx,
4958 )
4959 }
4960
4961 fn retain_remotely_created_models_impl(
4962 models: &Arc<Mutex<RemotelyCreatedModels>>,
4963 buffer_store: &Entity<BufferStore>,
4964 worktree_store: &Entity<WorktreeStore>,
4965 cx: &mut App,
4966 ) -> RemotelyCreatedModelGuard {
4967 {
4968 let mut remotely_create_models = models.lock();
4969 if remotely_create_models.retain_count == 0 {
4970 remotely_create_models.buffers = buffer_store.read(cx).buffers().collect();
4971 remotely_create_models.worktrees = worktree_store.read(cx).worktrees().collect();
4972 }
4973 remotely_create_models.retain_count += 1;
4974 }
4975 RemotelyCreatedModelGuard {
4976 remote_models: Arc::downgrade(&models),
4977 }
4978 }
4979
4980 async fn handle_create_buffer_for_peer(
4981 this: Entity<Self>,
4982 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4983 mut cx: AsyncApp,
4984 ) -> Result<()> {
4985 this.update(&mut cx, |this, cx| {
4986 this.buffer_store.update(cx, |buffer_store, cx| {
4987 buffer_store.handle_create_buffer_for_peer(
4988 envelope,
4989 this.replica_id(),
4990 this.capability(),
4991 cx,
4992 )
4993 })
4994 })?
4995 }
4996
4997 async fn handle_toggle_lsp_logs(
4998 project: Entity<Self>,
4999 envelope: TypedEnvelope<proto::ToggleLspLogs>,
5000 mut cx: AsyncApp,
5001 ) -> Result<()> {
5002 let toggled_log_kind =
5003 match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
5004 .context("invalid log type")?
5005 {
5006 proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
5007 proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
5008 proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
5009 };
5010 project.update(&mut cx, |_, cx| {
5011 cx.emit(Event::ToggleLspLogs {
5012 server_id: LanguageServerId::from_proto(envelope.payload.server_id),
5013 enabled: envelope.payload.enabled,
5014 toggled_log_kind,
5015 })
5016 })?;
5017 Ok(())
5018 }
5019
5020 async fn handle_synchronize_buffers(
5021 this: Entity<Self>,
5022 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5023 mut cx: AsyncApp,
5024 ) -> Result<proto::SynchronizeBuffersResponse> {
5025 let response = this.update(&mut cx, |this, cx| {
5026 let client = this.collab_client.clone();
5027 this.buffer_store.update(cx, |this, cx| {
5028 this.handle_synchronize_buffers(envelope, cx, client)
5029 })
5030 })??;
5031
5032 Ok(response)
5033 }
5034
5035 async fn handle_search_candidate_buffers(
5036 this: Entity<Self>,
5037 envelope: TypedEnvelope<proto::FindSearchCandidates>,
5038 mut cx: AsyncApp,
5039 ) -> Result<proto::FindSearchCandidatesResponse> {
5040 let peer_id = envelope.original_sender_id()?;
5041 let message = envelope.payload;
5042 let path_style = this.read_with(&cx, |this, cx| this.path_style(cx))?;
5043 let query =
5044 SearchQuery::from_proto(message.query.context("missing query field")?, path_style)?;
5045 let results = this.update(&mut cx, |this, cx| {
5046 this.search_impl(query, cx).matching_buffers(cx)
5047 })?;
5048
5049 let mut response = proto::FindSearchCandidatesResponse {
5050 buffer_ids: Vec::new(),
5051 };
5052
5053 while let Ok(buffer) = results.recv().await {
5054 this.update(&mut cx, |this, cx| {
5055 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5056 response.buffer_ids.push(buffer_id.to_proto());
5057 })?;
5058 }
5059
5060 Ok(response)
5061 }
5062
5063 async fn handle_open_buffer_by_id(
5064 this: Entity<Self>,
5065 envelope: TypedEnvelope<proto::OpenBufferById>,
5066 mut cx: AsyncApp,
5067 ) -> Result<proto::OpenBufferResponse> {
5068 let peer_id = envelope.original_sender_id()?;
5069 let buffer_id = BufferId::new(envelope.payload.id)?;
5070 let buffer = this
5071 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
5072 .await?;
5073 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5074 }
5075
5076 async fn handle_open_buffer_by_path(
5077 this: Entity<Self>,
5078 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5079 mut cx: AsyncApp,
5080 ) -> Result<proto::OpenBufferResponse> {
5081 let peer_id = envelope.original_sender_id()?;
5082 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5083 let path = RelPath::from_proto(&envelope.payload.path)?;
5084 let open_buffer = this
5085 .update(&mut cx, |this, cx| {
5086 this.open_buffer(ProjectPath { worktree_id, path }, cx)
5087 })?
5088 .await?;
5089 Project::respond_to_open_buffer_request(this, open_buffer, peer_id, &mut cx)
5090 }
5091
5092 async fn handle_open_new_buffer(
5093 this: Entity<Self>,
5094 envelope: TypedEnvelope<proto::OpenNewBuffer>,
5095 mut cx: AsyncApp,
5096 ) -> Result<proto::OpenBufferResponse> {
5097 let buffer = this
5098 .update(&mut cx, |this, cx| this.create_buffer(true, cx))?
5099 .await?;
5100 let peer_id = envelope.original_sender_id()?;
5101
5102 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5103 }
5104
5105 fn respond_to_open_buffer_request(
5106 this: Entity<Self>,
5107 buffer: Entity<Buffer>,
5108 peer_id: proto::PeerId,
5109 cx: &mut AsyncApp,
5110 ) -> Result<proto::OpenBufferResponse> {
5111 this.update(cx, |this, cx| {
5112 let is_private = buffer
5113 .read(cx)
5114 .file()
5115 .map(|f| f.is_private())
5116 .unwrap_or_default();
5117 anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
5118 Ok(proto::OpenBufferResponse {
5119 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
5120 })
5121 })?
5122 }
5123
5124 fn create_buffer_for_peer(
5125 &mut self,
5126 buffer: &Entity<Buffer>,
5127 peer_id: proto::PeerId,
5128 cx: &mut App,
5129 ) -> BufferId {
5130 self.buffer_store
5131 .update(cx, |buffer_store, cx| {
5132 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
5133 })
5134 .detach_and_log_err(cx);
5135 buffer.read(cx).remote_id()
5136 }
5137
5138 async fn handle_create_image_for_peer(
5139 this: Entity<Self>,
5140 envelope: TypedEnvelope<proto::CreateImageForPeer>,
5141 mut cx: AsyncApp,
5142 ) -> Result<()> {
5143 this.update(&mut cx, |this, cx| {
5144 this.image_store.update(cx, |image_store, cx| {
5145 image_store.handle_create_image_for_peer(envelope, cx)
5146 })
5147 })?
5148 .log_err();
5149 Ok(())
5150 }
5151
5152 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
5153 let project_id = match self.client_state {
5154 ProjectClientState::Remote {
5155 sharing_has_stopped,
5156 remote_id,
5157 ..
5158 } => {
5159 if sharing_has_stopped {
5160 return Task::ready(Err(anyhow!(
5161 "can't synchronize remote buffers on a readonly project"
5162 )));
5163 } else {
5164 remote_id
5165 }
5166 }
5167 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
5168 return Task::ready(Err(anyhow!(
5169 "can't synchronize remote buffers on a local project"
5170 )));
5171 }
5172 };
5173
5174 let client = self.collab_client.clone();
5175 cx.spawn(async move |this, cx| {
5176 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
5177 this.buffer_store.read(cx).buffer_version_info(cx)
5178 })?;
5179 let response = client
5180 .request(proto::SynchronizeBuffers {
5181 project_id,
5182 buffers,
5183 })
5184 .await?;
5185
5186 let send_updates_for_buffers = this.update(cx, |this, cx| {
5187 response
5188 .buffers
5189 .into_iter()
5190 .map(|buffer| {
5191 let client = client.clone();
5192 let buffer_id = match BufferId::new(buffer.id) {
5193 Ok(id) => id,
5194 Err(e) => {
5195 return Task::ready(Err(e));
5196 }
5197 };
5198 let remote_version = language::proto::deserialize_version(&buffer.version);
5199 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5200 let operations =
5201 buffer.read(cx).serialize_ops(Some(remote_version), cx);
5202 cx.background_spawn(async move {
5203 let operations = operations.await;
5204 for chunk in split_operations(operations) {
5205 client
5206 .request(proto::UpdateBuffer {
5207 project_id,
5208 buffer_id: buffer_id.into(),
5209 operations: chunk,
5210 })
5211 .await?;
5212 }
5213 anyhow::Ok(())
5214 })
5215 } else {
5216 Task::ready(Ok(()))
5217 }
5218 })
5219 .collect::<Vec<_>>()
5220 })?;
5221
5222 // Any incomplete buffers have open requests waiting. Request that the host sends
5223 // creates these buffers for us again to unblock any waiting futures.
5224 for id in incomplete_buffer_ids {
5225 cx.background_spawn(client.request(proto::OpenBufferById {
5226 project_id,
5227 id: id.into(),
5228 }))
5229 .detach();
5230 }
5231
5232 futures::future::join_all(send_updates_for_buffers)
5233 .await
5234 .into_iter()
5235 .collect()
5236 })
5237 }
5238
5239 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
5240 self.worktree_store.read(cx).worktree_metadata_protos(cx)
5241 }
5242
5243 /// Iterator of all open buffers that have unsaved changes
5244 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
5245 self.buffer_store.read(cx).buffers().filter_map(|buf| {
5246 let buf = buf.read(cx);
5247 if buf.is_dirty() {
5248 buf.project_path(cx)
5249 } else {
5250 None
5251 }
5252 })
5253 }
5254
5255 fn set_worktrees_from_proto(
5256 &mut self,
5257 worktrees: Vec<proto::WorktreeMetadata>,
5258 cx: &mut Context<Project>,
5259 ) -> Result<()> {
5260 self.worktree_store.update(cx, |worktree_store, cx| {
5261 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
5262 })
5263 }
5264
5265 fn set_collaborators_from_proto(
5266 &mut self,
5267 messages: Vec<proto::Collaborator>,
5268 cx: &mut Context<Self>,
5269 ) -> Result<()> {
5270 let mut collaborators = HashMap::default();
5271 for message in messages {
5272 let collaborator = Collaborator::from_proto(message)?;
5273 collaborators.insert(collaborator.peer_id, collaborator);
5274 }
5275 for old_peer_id in self.collaborators.keys() {
5276 if !collaborators.contains_key(old_peer_id) {
5277 cx.emit(Event::CollaboratorLeft(*old_peer_id));
5278 }
5279 }
5280 self.collaborators = collaborators;
5281 Ok(())
5282 }
5283
5284 pub fn supplementary_language_servers<'a>(
5285 &'a self,
5286 cx: &'a App,
5287 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
5288 self.lsp_store.read(cx).supplementary_language_servers()
5289 }
5290
5291 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
5292 let Some(language) = buffer.language().cloned() else {
5293 return false;
5294 };
5295 self.lsp_store.update(cx, |lsp_store, _| {
5296 let relevant_language_servers = lsp_store
5297 .languages
5298 .lsp_adapters(&language.name())
5299 .into_iter()
5300 .map(|lsp_adapter| lsp_adapter.name())
5301 .collect::<HashSet<_>>();
5302 lsp_store
5303 .language_server_statuses()
5304 .filter_map(|(server_id, server_status)| {
5305 relevant_language_servers
5306 .contains(&server_status.name)
5307 .then_some(server_id)
5308 })
5309 .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5310 .any(InlayHints::check_capabilities)
5311 })
5312 }
5313
5314 pub fn language_server_id_for_name(
5315 &self,
5316 buffer: &Buffer,
5317 name: &LanguageServerName,
5318 cx: &App,
5319 ) -> Option<LanguageServerId> {
5320 let language = buffer.language()?;
5321 let relevant_language_servers = self
5322 .languages
5323 .lsp_adapters(&language.name())
5324 .into_iter()
5325 .map(|lsp_adapter| lsp_adapter.name())
5326 .collect::<HashSet<_>>();
5327 if !relevant_language_servers.contains(name) {
5328 return None;
5329 }
5330 self.language_server_statuses(cx)
5331 .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
5332 .find_map(|(server_id, server_status)| {
5333 if &server_status.name == name {
5334 Some(server_id)
5335 } else {
5336 None
5337 }
5338 })
5339 }
5340
5341 #[cfg(any(test, feature = "test-support"))]
5342 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
5343 self.lsp_store.update(cx, |this, cx| {
5344 this.running_language_servers_for_local_buffer(buffer, cx)
5345 .next()
5346 .is_some()
5347 })
5348 }
5349
5350 pub fn git_init(
5351 &self,
5352 path: Arc<Path>,
5353 fallback_branch_name: String,
5354 cx: &App,
5355 ) -> Task<Result<()>> {
5356 self.git_store
5357 .read(cx)
5358 .git_init(path, fallback_branch_name, cx)
5359 }
5360
5361 pub fn buffer_store(&self) -> &Entity<BufferStore> {
5362 &self.buffer_store
5363 }
5364
5365 pub fn git_store(&self) -> &Entity<GitStore> {
5366 &self.git_store
5367 }
5368
5369 pub fn agent_server_store(&self) -> &Entity<AgentServerStore> {
5370 &self.agent_server_store
5371 }
5372
5373 #[cfg(test)]
5374 fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
5375 cx.spawn(async move |this, cx| {
5376 let scans_complete = this
5377 .read_with(cx, |this, cx| {
5378 this.worktrees(cx)
5379 .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
5380 .collect::<Vec<_>>()
5381 })
5382 .unwrap();
5383 join_all(scans_complete).await;
5384 let barriers = this
5385 .update(cx, |this, cx| {
5386 let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
5387 repos
5388 .into_iter()
5389 .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
5390 .collect::<Vec<_>>()
5391 })
5392 .unwrap();
5393 join_all(barriers).await;
5394 })
5395 }
5396
5397 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
5398 self.git_store.read(cx).active_repository()
5399 }
5400
5401 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
5402 self.git_store.read(cx).repositories()
5403 }
5404
5405 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
5406 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
5407 }
5408
5409 pub fn set_agent_location(
5410 &mut self,
5411 new_location: Option<AgentLocation>,
5412 cx: &mut Context<Self>,
5413 ) {
5414 if let Some(old_location) = self.agent_location.as_ref() {
5415 old_location
5416 .buffer
5417 .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
5418 .ok();
5419 }
5420
5421 if let Some(location) = new_location.as_ref() {
5422 location
5423 .buffer
5424 .update(cx, |buffer, cx| {
5425 buffer.set_agent_selections(
5426 Arc::from([language::Selection {
5427 id: 0,
5428 start: location.position,
5429 end: location.position,
5430 reversed: false,
5431 goal: language::SelectionGoal::None,
5432 }]),
5433 false,
5434 CursorShape::Hollow,
5435 cx,
5436 )
5437 })
5438 .ok();
5439 }
5440
5441 self.agent_location = new_location;
5442 cx.emit(Event::AgentLocationChanged);
5443 }
5444
5445 pub fn agent_location(&self) -> Option<AgentLocation> {
5446 self.agent_location.clone()
5447 }
5448
5449 pub fn path_style(&self, cx: &App) -> PathStyle {
5450 self.worktree_store.read(cx).path_style()
5451 }
5452
5453 pub fn contains_local_settings_file(
5454 &self,
5455 worktree_id: WorktreeId,
5456 rel_path: &RelPath,
5457 cx: &App,
5458 ) -> bool {
5459 self.worktree_for_id(worktree_id, cx)
5460 .map_or(false, |worktree| {
5461 worktree.read(cx).entry_for_path(rel_path).is_some()
5462 })
5463 }
5464
5465 pub fn update_local_settings_file(
5466 &self,
5467 worktree_id: WorktreeId,
5468 rel_path: Arc<RelPath>,
5469 cx: &mut App,
5470 update: impl 'static + Send + FnOnce(&mut settings::SettingsContent, &App),
5471 ) {
5472 let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {
5473 // todo(settings_ui) error?
5474 return;
5475 };
5476 cx.spawn(async move |cx| {
5477 let file = worktree
5478 .update(cx, |worktree, cx| worktree.load_file(&rel_path, cx))?
5479 .await
5480 .context("Failed to load settings file")?;
5481
5482 let has_bom = file.has_bom;
5483
5484 let new_text = cx.read_global::<SettingsStore, _>(|store, cx| {
5485 store.new_text_for_update(file.text, move |settings| update(settings, cx))
5486 })?;
5487 worktree
5488 .update(cx, |worktree, cx| {
5489 let line_ending = text::LineEnding::detect(&new_text);
5490 worktree.write_file(
5491 rel_path.clone(),
5492 new_text.into(),
5493 line_ending,
5494 encoding_rs::UTF_8,
5495 has_bom,
5496 cx,
5497 )
5498 })?
5499 .await
5500 .context("Failed to write settings file")?;
5501
5502 anyhow::Ok(())
5503 })
5504 .detach_and_log_err(cx);
5505 }
5506}
5507
5508pub struct PathMatchCandidateSet {
5509 pub snapshot: Snapshot,
5510 pub include_ignored: bool,
5511 pub include_root_name: bool,
5512 pub candidates: Candidates,
5513}
5514
5515pub enum Candidates {
5516 /// Only consider directories.
5517 Directories,
5518 /// Only consider files.
5519 Files,
5520 /// Consider directories and files.
5521 Entries,
5522}
5523
5524impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5525 type Candidates = PathMatchCandidateSetIter<'a>;
5526
5527 fn id(&self) -> usize {
5528 self.snapshot.id().to_usize()
5529 }
5530
5531 fn len(&self) -> usize {
5532 match self.candidates {
5533 Candidates::Files => {
5534 if self.include_ignored {
5535 self.snapshot.file_count()
5536 } else {
5537 self.snapshot.visible_file_count()
5538 }
5539 }
5540
5541 Candidates::Directories => {
5542 if self.include_ignored {
5543 self.snapshot.dir_count()
5544 } else {
5545 self.snapshot.visible_dir_count()
5546 }
5547 }
5548
5549 Candidates::Entries => {
5550 if self.include_ignored {
5551 self.snapshot.entry_count()
5552 } else {
5553 self.snapshot.visible_entry_count()
5554 }
5555 }
5556 }
5557 }
5558
5559 fn prefix(&self) -> Arc<RelPath> {
5560 if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
5561 self.snapshot.root_name().into()
5562 } else {
5563 RelPath::empty().into()
5564 }
5565 }
5566
5567 fn root_is_file(&self) -> bool {
5568 self.snapshot.root_entry().is_some_and(|f| f.is_file())
5569 }
5570
5571 fn path_style(&self) -> PathStyle {
5572 self.snapshot.path_style()
5573 }
5574
5575 fn candidates(&'a self, start: usize) -> Self::Candidates {
5576 PathMatchCandidateSetIter {
5577 traversal: match self.candidates {
5578 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5579 Candidates::Files => self.snapshot.files(self.include_ignored, start),
5580 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5581 },
5582 }
5583 }
5584}
5585
5586pub struct PathMatchCandidateSetIter<'a> {
5587 traversal: Traversal<'a>,
5588}
5589
5590impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5591 type Item = fuzzy::PathMatchCandidate<'a>;
5592
5593 fn next(&mut self) -> Option<Self::Item> {
5594 self.traversal
5595 .next()
5596 .map(|entry| fuzzy::PathMatchCandidate {
5597 is_dir: entry.kind.is_dir(),
5598 path: &entry.path,
5599 char_bag: entry.char_bag,
5600 })
5601 }
5602}
5603
5604impl EventEmitter<Event> for Project {}
5605
5606impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5607 fn from(val: &'a ProjectPath) -> Self {
5608 SettingsLocation {
5609 worktree_id: val.worktree_id,
5610 path: val.path.as_ref(),
5611 }
5612 }
5613}
5614
5615impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
5616 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5617 Self {
5618 worktree_id,
5619 path: path.into(),
5620 }
5621 }
5622}
5623
5624/// ResolvedPath is a path that has been resolved to either a ProjectPath
5625/// or an AbsPath and that *exists*.
5626#[derive(Debug, Clone)]
5627pub enum ResolvedPath {
5628 ProjectPath {
5629 project_path: ProjectPath,
5630 is_dir: bool,
5631 },
5632 AbsPath {
5633 path: String,
5634 is_dir: bool,
5635 },
5636}
5637
5638impl ResolvedPath {
5639 pub fn abs_path(&self) -> Option<&str> {
5640 match self {
5641 Self::AbsPath { path, .. } => Some(path),
5642 _ => None,
5643 }
5644 }
5645
5646 pub fn into_abs_path(self) -> Option<String> {
5647 match self {
5648 Self::AbsPath { path, .. } => Some(path),
5649 _ => None,
5650 }
5651 }
5652
5653 pub fn project_path(&self) -> Option<&ProjectPath> {
5654 match self {
5655 Self::ProjectPath { project_path, .. } => Some(project_path),
5656 _ => None,
5657 }
5658 }
5659
5660 pub fn is_file(&self) -> bool {
5661 !self.is_dir()
5662 }
5663
5664 pub fn is_dir(&self) -> bool {
5665 match self {
5666 Self::ProjectPath { is_dir, .. } => *is_dir,
5667 Self::AbsPath { is_dir, .. } => *is_dir,
5668 }
5669 }
5670}
5671
5672impl ProjectItem for Buffer {
5673 fn try_open(
5674 project: &Entity<Project>,
5675 path: &ProjectPath,
5676 cx: &mut App,
5677 ) -> Option<Task<Result<Entity<Self>>>> {
5678 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5679 }
5680
5681 fn entry_id(&self, _cx: &App) -> Option<ProjectEntryId> {
5682 File::from_dyn(self.file()).and_then(|file| file.project_entry_id())
5683 }
5684
5685 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5686 self.file().map(|file| ProjectPath {
5687 worktree_id: file.worktree_id(cx),
5688 path: file.path().clone(),
5689 })
5690 }
5691
5692 fn is_dirty(&self) -> bool {
5693 self.is_dirty()
5694 }
5695}
5696
5697impl Completion {
5698 pub fn kind(&self) -> Option<CompletionItemKind> {
5699 self.source
5700 // `lsp::CompletionListItemDefaults` has no `kind` field
5701 .lsp_completion(false)
5702 .and_then(|lsp_completion| lsp_completion.kind)
5703 }
5704
5705 pub fn label(&self) -> Option<String> {
5706 self.source
5707 .lsp_completion(false)
5708 .map(|lsp_completion| lsp_completion.label.clone())
5709 }
5710
5711 /// A key that can be used to sort completions when displaying
5712 /// them to the user.
5713 pub fn sort_key(&self) -> (usize, &str) {
5714 const DEFAULT_KIND_KEY: usize = 4;
5715 let kind_key = self
5716 .kind()
5717 .and_then(|lsp_completion_kind| match lsp_completion_kind {
5718 lsp::CompletionItemKind::KEYWORD => Some(0),
5719 lsp::CompletionItemKind::VARIABLE => Some(1),
5720 lsp::CompletionItemKind::CONSTANT => Some(2),
5721 lsp::CompletionItemKind::PROPERTY => Some(3),
5722 _ => None,
5723 })
5724 .unwrap_or(DEFAULT_KIND_KEY);
5725 (kind_key, self.label.filter_text())
5726 }
5727
5728 /// Whether this completion is a snippet.
5729 pub fn is_snippet_kind(&self) -> bool {
5730 matches!(
5731 &self.source,
5732 CompletionSource::Lsp { lsp_completion, .. }
5733 if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
5734 )
5735 }
5736
5737 /// Whether this completion is a snippet or snippet-style LSP completion.
5738 pub fn is_snippet(&self) -> bool {
5739 self.source
5740 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5741 .lsp_completion(true)
5742 .is_some_and(|lsp_completion| {
5743 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5744 })
5745 }
5746
5747 /// Returns the corresponding color for this completion.
5748 ///
5749 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5750 pub fn color(&self) -> Option<Hsla> {
5751 // `lsp::CompletionListItemDefaults` has no `kind` field
5752 let lsp_completion = self.source.lsp_completion(false)?;
5753 if lsp_completion.kind? == CompletionItemKind::COLOR {
5754 return color_extractor::extract_color(&lsp_completion);
5755 }
5756 None
5757 }
5758}
5759
5760fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5761 match level {
5762 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5763 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5764 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5765 }
5766}
5767
5768fn provide_inline_values(
5769 captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
5770 snapshot: &language::BufferSnapshot,
5771 max_row: usize,
5772) -> Vec<InlineValueLocation> {
5773 let mut variables = Vec::new();
5774 let mut variable_position = HashSet::default();
5775 let mut scopes = Vec::new();
5776
5777 let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
5778
5779 for (capture_range, capture_kind) in captures {
5780 match capture_kind {
5781 language::DebuggerTextObject::Variable => {
5782 let variable_name = snapshot
5783 .text_for_range(capture_range.clone())
5784 .collect::<String>();
5785 let point = snapshot.offset_to_point(capture_range.end);
5786
5787 while scopes
5788 .last()
5789 .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
5790 {
5791 scopes.pop();
5792 }
5793
5794 if point.row as usize > max_row {
5795 break;
5796 }
5797
5798 let scope = if scopes
5799 .last()
5800 .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
5801 {
5802 VariableScope::Global
5803 } else {
5804 VariableScope::Local
5805 };
5806
5807 if variable_position.insert(capture_range.end) {
5808 variables.push(InlineValueLocation {
5809 variable_name,
5810 scope,
5811 lookup: VariableLookupKind::Variable,
5812 row: point.row as usize,
5813 column: point.column as usize,
5814 });
5815 }
5816 }
5817 language::DebuggerTextObject::Scope => {
5818 while scopes.last().map_or_else(
5819 || false,
5820 |scope: &Range<usize>| {
5821 !(scope.contains(&capture_range.start)
5822 && scope.contains(&capture_range.end))
5823 },
5824 ) {
5825 scopes.pop();
5826 }
5827 scopes.push(capture_range);
5828 }
5829 }
5830 }
5831
5832 variables
5833}
5834
5835#[cfg(test)]
5836mod disable_ai_settings_tests {
5837 use super::*;
5838 use gpui::TestAppContext;
5839 use settings::Settings;
5840
5841 #[gpui::test]
5842 async fn test_disable_ai_settings_security(cx: &mut TestAppContext) {
5843 cx.update(|cx| {
5844 settings::init(cx);
5845
5846 // Test 1: Default is false (AI enabled)
5847 assert!(
5848 !DisableAiSettings::get_global(cx).disable_ai,
5849 "Default should allow AI"
5850 );
5851 });
5852
5853 let disable_true = serde_json::json!({
5854 "disable_ai": true
5855 })
5856 .to_string();
5857 let disable_false = serde_json::json!({
5858 "disable_ai": false
5859 })
5860 .to_string();
5861
5862 cx.update_global::<SettingsStore, _>(|store, cx| {
5863 store.set_user_settings(&disable_false, cx).unwrap();
5864 store.set_global_settings(&disable_true, cx).unwrap();
5865 });
5866 cx.update(|cx| {
5867 assert!(
5868 DisableAiSettings::get_global(cx).disable_ai,
5869 "Local false cannot override global true"
5870 );
5871 });
5872
5873 cx.update_global::<SettingsStore, _>(|store, cx| {
5874 store.set_global_settings(&disable_false, cx).unwrap();
5875 store.set_user_settings(&disable_true, cx).unwrap();
5876 });
5877
5878 cx.update(|cx| {
5879 assert!(
5880 DisableAiSettings::get_global(cx).disable_ai,
5881 "Local false cannot override global true"
5882 );
5883 });
5884 }
5885}