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