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