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