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