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, 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().into_owned())
895 .or_else(|| std::env::home_dir().map(|dir| dir.to_string_lossy().into_owned()))
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_unix_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_paths(
4045 (a.path().as_std_path(), true),
4046 (b.path().as_std_path(), true),
4047 ),
4048 });
4049 for buffer in buffers {
4050 tx.send_blocking(buffer.clone()).unwrap()
4051 }
4052
4053 rx
4054 }
4055
4056 fn find_search_candidates_remote(
4057 &mut self,
4058 query: &SearchQuery,
4059 limit: usize,
4060 cx: &mut Context<Project>,
4061 ) -> Receiver<Entity<Buffer>> {
4062 let (tx, rx) = smol::channel::unbounded();
4063
4064 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.remote_client
4065 {
4066 (ssh_client.read(cx).proto_client(), 0)
4067 } else if let Some(remote_id) = self.remote_id() {
4068 (self.collab_client.clone().into(), remote_id)
4069 } else {
4070 return rx;
4071 };
4072
4073 let request = client.request(proto::FindSearchCandidates {
4074 project_id: remote_id,
4075 query: Some(query.to_proto()),
4076 limit: limit as _,
4077 });
4078 let guard = self.retain_remotely_created_models(cx);
4079
4080 cx.spawn(async move |project, cx| {
4081 let response = request.await?;
4082 for buffer_id in response.buffer_ids {
4083 let buffer_id = BufferId::new(buffer_id)?;
4084 let buffer = project
4085 .update(cx, |project, cx| {
4086 project.buffer_store.update(cx, |buffer_store, cx| {
4087 buffer_store.wait_for_remote_buffer(buffer_id, cx)
4088 })
4089 })?
4090 .await?;
4091 let _ = tx.send(buffer).await;
4092 }
4093
4094 drop(guard);
4095 anyhow::Ok(())
4096 })
4097 .detach_and_log_err(cx);
4098 rx
4099 }
4100
4101 pub fn request_lsp<R: LspCommand>(
4102 &mut self,
4103 buffer_handle: Entity<Buffer>,
4104 server: LanguageServerToQuery,
4105 request: R,
4106 cx: &mut Context<Self>,
4107 ) -> Task<Result<R::Response>>
4108 where
4109 <R::LspRequest as lsp::request::Request>::Result: Send,
4110 <R::LspRequest as lsp::request::Request>::Params: Send,
4111 {
4112 let guard = self.retain_remotely_created_models(cx);
4113 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4114 lsp_store.request_lsp(buffer_handle, server, request, cx)
4115 });
4116 cx.background_spawn(async move {
4117 let result = task.await;
4118 drop(guard);
4119 result
4120 })
4121 }
4122
4123 /// Move a worktree to a new position in the worktree order.
4124 ///
4125 /// The worktree will moved to the opposite side of the destination worktree.
4126 ///
4127 /// # Example
4128 ///
4129 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4130 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4131 ///
4132 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4133 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4134 ///
4135 /// # Errors
4136 ///
4137 /// An error will be returned if the worktree or destination worktree are not found.
4138 pub fn move_worktree(
4139 &mut self,
4140 source: WorktreeId,
4141 destination: WorktreeId,
4142 cx: &mut Context<Self>,
4143 ) -> Result<()> {
4144 self.worktree_store.update(cx, |worktree_store, cx| {
4145 worktree_store.move_worktree(source, destination, cx)
4146 })
4147 }
4148
4149 pub fn find_or_create_worktree(
4150 &mut self,
4151 abs_path: impl AsRef<Path>,
4152 visible: bool,
4153 cx: &mut Context<Self>,
4154 ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
4155 self.worktree_store.update(cx, |worktree_store, cx| {
4156 worktree_store.find_or_create_worktree(abs_path, visible, cx)
4157 })
4158 }
4159
4160 pub fn find_worktree(
4161 &self,
4162 abs_path: &Path,
4163 cx: &App,
4164 ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
4165 self.worktree_store.read(cx).find_worktree(abs_path, cx)
4166 }
4167
4168 pub fn is_shared(&self) -> bool {
4169 match &self.client_state {
4170 ProjectClientState::Shared { .. } => true,
4171 ProjectClientState::Local => false,
4172 ProjectClientState::Remote { .. } => true,
4173 }
4174 }
4175
4176 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4177 pub fn resolve_path_in_buffer(
4178 &self,
4179 path: &str,
4180 buffer: &Entity<Buffer>,
4181 cx: &mut Context<Self>,
4182 ) -> Task<Option<ResolvedPath>> {
4183 if util::paths::is_absolute(path, self.path_style(cx)) || path.starts_with("~") {
4184 self.resolve_abs_path(path, cx)
4185 } else {
4186 self.resolve_path_in_worktrees(path, buffer, cx)
4187 }
4188 }
4189
4190 pub fn resolve_abs_file_path(
4191 &self,
4192 path: &str,
4193 cx: &mut Context<Self>,
4194 ) -> Task<Option<ResolvedPath>> {
4195 let resolve_task = self.resolve_abs_path(path, cx);
4196 cx.background_spawn(async move {
4197 let resolved_path = resolve_task.await;
4198 resolved_path.filter(|path| path.is_file())
4199 })
4200 }
4201
4202 pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4203 if self.is_local() {
4204 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4205 let fs = self.fs.clone();
4206 cx.background_spawn(async move {
4207 let metadata = fs.metadata(&expanded).await.ok().flatten();
4208
4209 metadata.map(|metadata| ResolvedPath::AbsPath {
4210 path: expanded.to_string_lossy().into_owned(),
4211 is_dir: metadata.is_dir,
4212 })
4213 })
4214 } else if let Some(ssh_client) = self.remote_client.as_ref() {
4215 let request = ssh_client
4216 .read(cx)
4217 .proto_client()
4218 .request(proto::GetPathMetadata {
4219 project_id: REMOTE_SERVER_PROJECT_ID,
4220 path: path.into(),
4221 });
4222 cx.background_spawn(async move {
4223 let response = request.await.log_err()?;
4224 if response.exists {
4225 Some(ResolvedPath::AbsPath {
4226 path: response.path,
4227 is_dir: response.is_dir,
4228 })
4229 } else {
4230 None
4231 }
4232 })
4233 } else {
4234 Task::ready(None)
4235 }
4236 }
4237
4238 fn resolve_path_in_worktrees(
4239 &self,
4240 path: &str,
4241 buffer: &Entity<Buffer>,
4242 cx: &mut Context<Self>,
4243 ) -> Task<Option<ResolvedPath>> {
4244 let mut candidates = vec![];
4245 let path_style = self.path_style(cx);
4246 if let Ok(path) = RelPath::new(path.as_ref(), path_style) {
4247 candidates.push(path.into_arc());
4248 }
4249
4250 if let Some(file) = buffer.read(cx).file()
4251 && let Some(dir) = file.path().parent()
4252 {
4253 if let Some(joined) = path_style.join(&*dir.display(path_style), path)
4254 && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
4255 {
4256 candidates.push(joined.into_arc());
4257 }
4258 }
4259
4260 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4261 let worktrees_with_ids: Vec<_> = self
4262 .worktrees(cx)
4263 .map(|worktree| {
4264 let id = worktree.read(cx).id();
4265 (worktree, id)
4266 })
4267 .collect();
4268
4269 cx.spawn(async move |_, cx| {
4270 if let Some(buffer_worktree_id) = buffer_worktree_id
4271 && let Some((worktree, _)) = worktrees_with_ids
4272 .iter()
4273 .find(|(_, id)| *id == buffer_worktree_id)
4274 {
4275 for candidate in candidates.iter() {
4276 if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4277 return Some(path);
4278 }
4279 }
4280 }
4281 for (worktree, id) in worktrees_with_ids {
4282 if Some(id) == buffer_worktree_id {
4283 continue;
4284 }
4285 for candidate in candidates.iter() {
4286 if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4287 return Some(path);
4288 }
4289 }
4290 }
4291 None
4292 })
4293 }
4294
4295 fn resolve_path_in_worktree(
4296 worktree: &Entity<Worktree>,
4297 path: &RelPath,
4298 cx: &mut AsyncApp,
4299 ) -> Option<ResolvedPath> {
4300 worktree
4301 .read_with(cx, |worktree, _| {
4302 worktree.entry_for_path(path).map(|entry| {
4303 let project_path = ProjectPath {
4304 worktree_id: worktree.id(),
4305 path: entry.path.clone(),
4306 };
4307 ResolvedPath::ProjectPath {
4308 project_path,
4309 is_dir: entry.is_dir(),
4310 }
4311 })
4312 })
4313 .ok()?
4314 }
4315
4316 pub fn list_directory(
4317 &self,
4318 query: String,
4319 cx: &mut Context<Self>,
4320 ) -> Task<Result<Vec<DirectoryItem>>> {
4321 if self.is_local() {
4322 DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4323 } else if let Some(session) = self.remote_client.as_ref() {
4324 let request = proto::ListRemoteDirectory {
4325 dev_server_id: REMOTE_SERVER_PROJECT_ID,
4326 path: query,
4327 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4328 };
4329
4330 let response = session.read(cx).proto_client().request(request);
4331 cx.background_spawn(async move {
4332 let proto::ListRemoteDirectoryResponse {
4333 entries,
4334 entry_info,
4335 } = response.await?;
4336 Ok(entries
4337 .into_iter()
4338 .zip(entry_info)
4339 .map(|(entry, info)| DirectoryItem {
4340 path: PathBuf::from(entry),
4341 is_dir: info.is_dir,
4342 })
4343 .collect())
4344 })
4345 } else {
4346 Task::ready(Err(anyhow!("cannot list directory in remote project")))
4347 }
4348 }
4349
4350 pub fn create_worktree(
4351 &mut self,
4352 abs_path: impl AsRef<Path>,
4353 visible: bool,
4354 cx: &mut Context<Self>,
4355 ) -> Task<Result<Entity<Worktree>>> {
4356 self.worktree_store.update(cx, |worktree_store, cx| {
4357 worktree_store.create_worktree(abs_path, visible, cx)
4358 })
4359 }
4360
4361 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4362 self.worktree_store.update(cx, |worktree_store, cx| {
4363 worktree_store.remove_worktree(id_to_remove, cx);
4364 });
4365 }
4366
4367 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4368 self.worktree_store.update(cx, |worktree_store, cx| {
4369 worktree_store.add(worktree, cx);
4370 });
4371 }
4372
4373 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4374 let new_active_entry = entry.and_then(|project_path| {
4375 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4376 let entry = worktree.read(cx).entry_for_path(&project_path.path)?;
4377 Some(entry.id)
4378 });
4379 if new_active_entry != self.active_entry {
4380 self.active_entry = new_active_entry;
4381 self.lsp_store.update(cx, |lsp_store, _| {
4382 lsp_store.set_active_entry(new_active_entry);
4383 });
4384 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4385 }
4386 }
4387
4388 pub fn language_servers_running_disk_based_diagnostics<'a>(
4389 &'a self,
4390 cx: &'a App,
4391 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4392 self.lsp_store
4393 .read(cx)
4394 .language_servers_running_disk_based_diagnostics()
4395 }
4396
4397 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4398 self.lsp_store
4399 .read(cx)
4400 .diagnostic_summary(include_ignored, cx)
4401 }
4402
4403 /// Returns a summary of the diagnostics for the provided project path only.
4404 pub fn diagnostic_summary_for_path(&self, path: &ProjectPath, cx: &App) -> DiagnosticSummary {
4405 self.lsp_store
4406 .read(cx)
4407 .diagnostic_summary_for_path(path, cx)
4408 }
4409
4410 pub fn diagnostic_summaries<'a>(
4411 &'a self,
4412 include_ignored: bool,
4413 cx: &'a App,
4414 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4415 self.lsp_store
4416 .read(cx)
4417 .diagnostic_summaries(include_ignored, cx)
4418 }
4419
4420 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4421 self.active_entry
4422 }
4423
4424 pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
4425 self.worktree_store.read(cx).entry_for_path(path, cx)
4426 }
4427
4428 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4429 let worktree = self.worktree_for_entry(entry_id, cx)?;
4430 let worktree = worktree.read(cx);
4431 let worktree_id = worktree.id();
4432 let path = worktree.entry_for_id(entry_id)?.path.clone();
4433 Some(ProjectPath { worktree_id, path })
4434 }
4435
4436 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4437 Some(
4438 self.worktree_for_id(project_path.worktree_id, cx)?
4439 .read(cx)
4440 .absolutize(&project_path.path),
4441 )
4442 }
4443
4444 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4445 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4446 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4447 /// the first visible worktree that has an entry for that relative path.
4448 ///
4449 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4450 /// root name from paths.
4451 ///
4452 /// # Arguments
4453 ///
4454 /// * `path` - An absolute path, or a full path that starts with a worktree root name, or a
4455 /// relative path within a visible worktree.
4456 /// * `cx` - A reference to the `AppContext`.
4457 ///
4458 /// # Returns
4459 ///
4460 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4461 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4462 let path_style = self.path_style(cx);
4463 let path = path.as_ref();
4464 let worktree_store = self.worktree_store.read(cx);
4465
4466 if is_absolute(&path.to_string_lossy(), path_style) {
4467 for worktree in worktree_store.visible_worktrees(cx) {
4468 let worktree_abs_path = worktree.read(cx).abs_path();
4469
4470 if let Ok(relative_path) = path.strip_prefix(worktree_abs_path)
4471 && let Ok(path) = RelPath::new(relative_path, path_style)
4472 {
4473 return Some(ProjectPath {
4474 worktree_id: worktree.read(cx).id(),
4475 path: path.into_arc(),
4476 });
4477 }
4478 }
4479 } else {
4480 for worktree in worktree_store.visible_worktrees(cx) {
4481 let worktree_root_name = worktree.read(cx).root_name();
4482 if let Ok(relative_path) = path.strip_prefix(worktree_root_name.as_std_path())
4483 && let Ok(path) = RelPath::new(relative_path, path_style)
4484 {
4485 return Some(ProjectPath {
4486 worktree_id: worktree.read(cx).id(),
4487 path: path.into_arc(),
4488 });
4489 }
4490 }
4491
4492 for worktree in worktree_store.visible_worktrees(cx) {
4493 let worktree = worktree.read(cx);
4494 if let Ok(path) = RelPath::new(path, path_style)
4495 && let Some(entry) = worktree.entry_for_path(&path)
4496 {
4497 return Some(ProjectPath {
4498 worktree_id: worktree.id(),
4499 path: entry.path.clone(),
4500 });
4501 }
4502 }
4503 }
4504
4505 None
4506 }
4507
4508 /// If there's only one visible worktree, returns the given worktree-relative path with no prefix.
4509 ///
4510 /// Otherwise, returns the full path for the project path (obtained by prefixing the worktree-relative path with the name of the worktree).
4511 pub fn short_full_path_for_project_path(
4512 &self,
4513 project_path: &ProjectPath,
4514 cx: &App,
4515 ) -> Option<String> {
4516 let path_style = self.path_style(cx);
4517 if self.visible_worktrees(cx).take(2).count() < 2 {
4518 return Some(project_path.path.display(path_style).to_string());
4519 }
4520 self.worktree_for_id(project_path.worktree_id, cx)
4521 .map(|worktree| {
4522 let worktree_name = worktree.read(cx).root_name();
4523 worktree_name
4524 .join(&project_path.path)
4525 .display(path_style)
4526 .to_string()
4527 })
4528 }
4529
4530 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4531 self.find_worktree(abs_path, cx)
4532 .map(|(worktree, relative_path)| ProjectPath {
4533 worktree_id: worktree.read(cx).id(),
4534 path: relative_path,
4535 })
4536 }
4537
4538 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4539 Some(
4540 self.worktree_for_id(project_path.worktree_id, cx)?
4541 .read(cx)
4542 .abs_path()
4543 .to_path_buf(),
4544 )
4545 }
4546
4547 pub fn blame_buffer(
4548 &self,
4549 buffer: &Entity<Buffer>,
4550 version: Option<clock::Global>,
4551 cx: &mut App,
4552 ) -> Task<Result<Option<Blame>>> {
4553 self.git_store.update(cx, |git_store, cx| {
4554 git_store.blame_buffer(buffer, version, cx)
4555 })
4556 }
4557
4558 pub fn get_permalink_to_line(
4559 &self,
4560 buffer: &Entity<Buffer>,
4561 selection: Range<u32>,
4562 cx: &mut App,
4563 ) -> Task<Result<url::Url>> {
4564 self.git_store.update(cx, |git_store, cx| {
4565 git_store.get_permalink_to_line(buffer, selection, cx)
4566 })
4567 }
4568
4569 // RPC message handlers
4570
4571 async fn handle_unshare_project(
4572 this: Entity<Self>,
4573 _: TypedEnvelope<proto::UnshareProject>,
4574 mut cx: AsyncApp,
4575 ) -> Result<()> {
4576 this.update(&mut cx, |this, cx| {
4577 if this.is_local() || this.is_via_remote_server() {
4578 this.unshare(cx)?;
4579 } else {
4580 this.disconnected_from_host(cx);
4581 }
4582 Ok(())
4583 })?
4584 }
4585
4586 async fn handle_add_collaborator(
4587 this: Entity<Self>,
4588 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4589 mut cx: AsyncApp,
4590 ) -> Result<()> {
4591 let collaborator = envelope
4592 .payload
4593 .collaborator
4594 .take()
4595 .context("empty collaborator")?;
4596
4597 let collaborator = Collaborator::from_proto(collaborator)?;
4598 this.update(&mut cx, |this, cx| {
4599 this.buffer_store.update(cx, |buffer_store, _| {
4600 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4601 });
4602 this.breakpoint_store.read(cx).broadcast();
4603 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4604 this.collaborators
4605 .insert(collaborator.peer_id, collaborator);
4606 })?;
4607
4608 Ok(())
4609 }
4610
4611 async fn handle_update_project_collaborator(
4612 this: Entity<Self>,
4613 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4614 mut cx: AsyncApp,
4615 ) -> Result<()> {
4616 let old_peer_id = envelope
4617 .payload
4618 .old_peer_id
4619 .context("missing old peer id")?;
4620 let new_peer_id = envelope
4621 .payload
4622 .new_peer_id
4623 .context("missing new peer id")?;
4624 this.update(&mut cx, |this, cx| {
4625 let collaborator = this
4626 .collaborators
4627 .remove(&old_peer_id)
4628 .context("received UpdateProjectCollaborator for unknown peer")?;
4629 let is_host = collaborator.is_host;
4630 this.collaborators.insert(new_peer_id, collaborator);
4631
4632 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4633 this.buffer_store.update(cx, |buffer_store, _| {
4634 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4635 });
4636
4637 if is_host {
4638 this.buffer_store
4639 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4640 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4641 .unwrap();
4642 cx.emit(Event::HostReshared);
4643 }
4644
4645 cx.emit(Event::CollaboratorUpdated {
4646 old_peer_id,
4647 new_peer_id,
4648 });
4649 Ok(())
4650 })?
4651 }
4652
4653 async fn handle_remove_collaborator(
4654 this: Entity<Self>,
4655 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4656 mut cx: AsyncApp,
4657 ) -> Result<()> {
4658 this.update(&mut cx, |this, cx| {
4659 let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4660 let replica_id = this
4661 .collaborators
4662 .remove(&peer_id)
4663 .with_context(|| format!("unknown peer {peer_id:?}"))?
4664 .replica_id;
4665 this.buffer_store.update(cx, |buffer_store, cx| {
4666 buffer_store.forget_shared_buffers_for(&peer_id);
4667 for buffer in buffer_store.buffers() {
4668 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4669 }
4670 });
4671 this.git_store.update(cx, |git_store, _| {
4672 git_store.forget_shared_diffs_for(&peer_id);
4673 });
4674
4675 cx.emit(Event::CollaboratorLeft(peer_id));
4676 Ok(())
4677 })?
4678 }
4679
4680 async fn handle_update_project(
4681 this: Entity<Self>,
4682 envelope: TypedEnvelope<proto::UpdateProject>,
4683 mut cx: AsyncApp,
4684 ) -> Result<()> {
4685 this.update(&mut cx, |this, cx| {
4686 // Don't handle messages that were sent before the response to us joining the project
4687 if envelope.message_id > this.join_project_response_message_id {
4688 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4689 }
4690 Ok(())
4691 })?
4692 }
4693
4694 async fn handle_toast(
4695 this: Entity<Self>,
4696 envelope: TypedEnvelope<proto::Toast>,
4697 mut cx: AsyncApp,
4698 ) -> Result<()> {
4699 this.update(&mut cx, |_, cx| {
4700 cx.emit(Event::Toast {
4701 notification_id: envelope.payload.notification_id.into(),
4702 message: envelope.payload.message,
4703 });
4704 Ok(())
4705 })?
4706 }
4707
4708 async fn handle_language_server_prompt_request(
4709 this: Entity<Self>,
4710 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4711 mut cx: AsyncApp,
4712 ) -> Result<proto::LanguageServerPromptResponse> {
4713 let (tx, rx) = smol::channel::bounded(1);
4714 let actions: Vec<_> = envelope
4715 .payload
4716 .actions
4717 .into_iter()
4718 .map(|action| MessageActionItem {
4719 title: action,
4720 properties: Default::default(),
4721 })
4722 .collect();
4723 this.update(&mut cx, |_, cx| {
4724 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4725 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4726 message: envelope.payload.message,
4727 actions: actions.clone(),
4728 lsp_name: envelope.payload.lsp_name,
4729 response_channel: tx,
4730 }));
4731
4732 anyhow::Ok(())
4733 })??;
4734
4735 // We drop `this` to avoid holding a reference in this future for too
4736 // long.
4737 // If we keep the reference, we might not drop the `Project` early
4738 // enough when closing a window and it will only get releases on the
4739 // next `flush_effects()` call.
4740 drop(this);
4741
4742 let mut rx = pin!(rx);
4743 let answer = rx.next().await;
4744
4745 Ok(LanguageServerPromptResponse {
4746 action_response: answer.and_then(|answer| {
4747 actions
4748 .iter()
4749 .position(|action| *action == answer)
4750 .map(|index| index as u64)
4751 }),
4752 })
4753 }
4754
4755 async fn handle_hide_toast(
4756 this: Entity<Self>,
4757 envelope: TypedEnvelope<proto::HideToast>,
4758 mut cx: AsyncApp,
4759 ) -> Result<()> {
4760 this.update(&mut cx, |_, cx| {
4761 cx.emit(Event::HideToast {
4762 notification_id: envelope.payload.notification_id.into(),
4763 });
4764 Ok(())
4765 })?
4766 }
4767
4768 // Collab sends UpdateWorktree protos as messages
4769 async fn handle_update_worktree(
4770 this: Entity<Self>,
4771 envelope: TypedEnvelope<proto::UpdateWorktree>,
4772 mut cx: AsyncApp,
4773 ) -> Result<()> {
4774 this.update(&mut cx, |this, cx| {
4775 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4776 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4777 worktree.update(cx, |worktree, _| {
4778 let worktree = worktree.as_remote_mut().unwrap();
4779 worktree.update_from_remote(envelope.payload);
4780 });
4781 }
4782 Ok(())
4783 })?
4784 }
4785
4786 async fn handle_update_buffer_from_remote_server(
4787 this: Entity<Self>,
4788 envelope: TypedEnvelope<proto::UpdateBuffer>,
4789 cx: AsyncApp,
4790 ) -> Result<proto::Ack> {
4791 let buffer_store = this.read_with(&cx, |this, cx| {
4792 if let Some(remote_id) = this.remote_id() {
4793 let mut payload = envelope.payload.clone();
4794 payload.project_id = remote_id;
4795 cx.background_spawn(this.collab_client.request(payload))
4796 .detach_and_log_err(cx);
4797 }
4798 this.buffer_store.clone()
4799 })?;
4800 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4801 }
4802
4803 async fn handle_update_buffer(
4804 this: Entity<Self>,
4805 envelope: TypedEnvelope<proto::UpdateBuffer>,
4806 cx: AsyncApp,
4807 ) -> Result<proto::Ack> {
4808 let buffer_store = this.read_with(&cx, |this, cx| {
4809 if let Some(ssh) = &this.remote_client {
4810 let mut payload = envelope.payload.clone();
4811 payload.project_id = REMOTE_SERVER_PROJECT_ID;
4812 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4813 .detach_and_log_err(cx);
4814 }
4815 this.buffer_store.clone()
4816 })?;
4817 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4818 }
4819
4820 fn retain_remotely_created_models(
4821 &mut self,
4822 cx: &mut Context<Self>,
4823 ) -> RemotelyCreatedModelGuard {
4824 {
4825 let mut remotely_create_models = self.remotely_created_models.lock();
4826 if remotely_create_models.retain_count == 0 {
4827 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4828 remotely_create_models.worktrees =
4829 self.worktree_store.read(cx).worktrees().collect();
4830 }
4831 remotely_create_models.retain_count += 1;
4832 }
4833 RemotelyCreatedModelGuard {
4834 remote_models: Arc::downgrade(&self.remotely_created_models),
4835 }
4836 }
4837
4838 async fn handle_create_buffer_for_peer(
4839 this: Entity<Self>,
4840 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4841 mut cx: AsyncApp,
4842 ) -> Result<()> {
4843 this.update(&mut cx, |this, cx| {
4844 this.buffer_store.update(cx, |buffer_store, cx| {
4845 buffer_store.handle_create_buffer_for_peer(
4846 envelope,
4847 this.replica_id(),
4848 this.capability(),
4849 cx,
4850 )
4851 })
4852 })?
4853 }
4854
4855 async fn handle_toggle_lsp_logs(
4856 project: Entity<Self>,
4857 envelope: TypedEnvelope<proto::ToggleLspLogs>,
4858 mut cx: AsyncApp,
4859 ) -> Result<()> {
4860 let toggled_log_kind =
4861 match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
4862 .context("invalid log type")?
4863 {
4864 proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
4865 proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
4866 proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
4867 };
4868 project.update(&mut cx, |_, cx| {
4869 cx.emit(Event::ToggleLspLogs {
4870 server_id: LanguageServerId::from_proto(envelope.payload.server_id),
4871 enabled: envelope.payload.enabled,
4872 toggled_log_kind,
4873 })
4874 })?;
4875 Ok(())
4876 }
4877
4878 async fn handle_synchronize_buffers(
4879 this: Entity<Self>,
4880 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4881 mut cx: AsyncApp,
4882 ) -> Result<proto::SynchronizeBuffersResponse> {
4883 let response = this.update(&mut cx, |this, cx| {
4884 let client = this.collab_client.clone();
4885 this.buffer_store.update(cx, |this, cx| {
4886 this.handle_synchronize_buffers(envelope, cx, client)
4887 })
4888 })??;
4889
4890 Ok(response)
4891 }
4892
4893 async fn handle_search_candidate_buffers(
4894 this: Entity<Self>,
4895 envelope: TypedEnvelope<proto::FindSearchCandidates>,
4896 mut cx: AsyncApp,
4897 ) -> Result<proto::FindSearchCandidatesResponse> {
4898 let peer_id = envelope.original_sender_id()?;
4899 let message = envelope.payload;
4900 let path_style = this.read_with(&cx, |this, cx| this.path_style(cx))?;
4901 let query =
4902 SearchQuery::from_proto(message.query.context("missing query field")?, path_style)?;
4903 let results = this.update(&mut cx, |this, cx| {
4904 this.find_search_candidate_buffers(&query, message.limit as _, cx)
4905 })?;
4906
4907 let mut response = proto::FindSearchCandidatesResponse {
4908 buffer_ids: Vec::new(),
4909 };
4910
4911 while let Ok(buffer) = results.recv().await {
4912 this.update(&mut cx, |this, cx| {
4913 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4914 response.buffer_ids.push(buffer_id.to_proto());
4915 })?;
4916 }
4917
4918 Ok(response)
4919 }
4920
4921 async fn handle_open_buffer_by_id(
4922 this: Entity<Self>,
4923 envelope: TypedEnvelope<proto::OpenBufferById>,
4924 mut cx: AsyncApp,
4925 ) -> Result<proto::OpenBufferResponse> {
4926 let peer_id = envelope.original_sender_id()?;
4927 let buffer_id = BufferId::new(envelope.payload.id)?;
4928 let buffer = this
4929 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4930 .await?;
4931 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4932 }
4933
4934 async fn handle_open_buffer_by_path(
4935 this: Entity<Self>,
4936 envelope: TypedEnvelope<proto::OpenBufferByPath>,
4937 mut cx: AsyncApp,
4938 ) -> Result<proto::OpenBufferResponse> {
4939 let peer_id = envelope.original_sender_id()?;
4940 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4941 let path = RelPath::from_proto(&envelope.payload.path)?;
4942 let open_buffer = this
4943 .update(&mut cx, |this, cx| {
4944 this.open_buffer(ProjectPath { worktree_id, path }, cx)
4945 })?
4946 .await?;
4947 Project::respond_to_open_buffer_request(this, open_buffer, peer_id, &mut cx)
4948 }
4949
4950 async fn handle_open_new_buffer(
4951 this: Entity<Self>,
4952 envelope: TypedEnvelope<proto::OpenNewBuffer>,
4953 mut cx: AsyncApp,
4954 ) -> Result<proto::OpenBufferResponse> {
4955 let buffer = this
4956 .update(&mut cx, |this, cx| this.create_buffer(true, cx))?
4957 .await?;
4958 let peer_id = envelope.original_sender_id()?;
4959
4960 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4961 }
4962
4963 fn respond_to_open_buffer_request(
4964 this: Entity<Self>,
4965 buffer: Entity<Buffer>,
4966 peer_id: proto::PeerId,
4967 cx: &mut AsyncApp,
4968 ) -> Result<proto::OpenBufferResponse> {
4969 this.update(cx, |this, cx| {
4970 let is_private = buffer
4971 .read(cx)
4972 .file()
4973 .map(|f| f.is_private())
4974 .unwrap_or_default();
4975 anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
4976 Ok(proto::OpenBufferResponse {
4977 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4978 })
4979 })?
4980 }
4981
4982 fn create_buffer_for_peer(
4983 &mut self,
4984 buffer: &Entity<Buffer>,
4985 peer_id: proto::PeerId,
4986 cx: &mut App,
4987 ) -> BufferId {
4988 self.buffer_store
4989 .update(cx, |buffer_store, cx| {
4990 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4991 })
4992 .detach_and_log_err(cx);
4993 buffer.read(cx).remote_id()
4994 }
4995
4996 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4997 let project_id = match self.client_state {
4998 ProjectClientState::Remote {
4999 sharing_has_stopped,
5000 remote_id,
5001 ..
5002 } => {
5003 if sharing_has_stopped {
5004 return Task::ready(Err(anyhow!(
5005 "can't synchronize remote buffers on a readonly project"
5006 )));
5007 } else {
5008 remote_id
5009 }
5010 }
5011 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
5012 return Task::ready(Err(anyhow!(
5013 "can't synchronize remote buffers on a local project"
5014 )));
5015 }
5016 };
5017
5018 let client = self.collab_client.clone();
5019 cx.spawn(async move |this, cx| {
5020 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
5021 this.buffer_store.read(cx).buffer_version_info(cx)
5022 })?;
5023 let response = client
5024 .request(proto::SynchronizeBuffers {
5025 project_id,
5026 buffers,
5027 })
5028 .await?;
5029
5030 let send_updates_for_buffers = this.update(cx, |this, cx| {
5031 response
5032 .buffers
5033 .into_iter()
5034 .map(|buffer| {
5035 let client = client.clone();
5036 let buffer_id = match BufferId::new(buffer.id) {
5037 Ok(id) => id,
5038 Err(e) => {
5039 return Task::ready(Err(e));
5040 }
5041 };
5042 let remote_version = language::proto::deserialize_version(&buffer.version);
5043 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5044 let operations =
5045 buffer.read(cx).serialize_ops(Some(remote_version), cx);
5046 cx.background_spawn(async move {
5047 let operations = operations.await;
5048 for chunk in split_operations(operations) {
5049 client
5050 .request(proto::UpdateBuffer {
5051 project_id,
5052 buffer_id: buffer_id.into(),
5053 operations: chunk,
5054 })
5055 .await?;
5056 }
5057 anyhow::Ok(())
5058 })
5059 } else {
5060 Task::ready(Ok(()))
5061 }
5062 })
5063 .collect::<Vec<_>>()
5064 })?;
5065
5066 // Any incomplete buffers have open requests waiting. Request that the host sends
5067 // creates these buffers for us again to unblock any waiting futures.
5068 for id in incomplete_buffer_ids {
5069 cx.background_spawn(client.request(proto::OpenBufferById {
5070 project_id,
5071 id: id.into(),
5072 }))
5073 .detach();
5074 }
5075
5076 futures::future::join_all(send_updates_for_buffers)
5077 .await
5078 .into_iter()
5079 .collect()
5080 })
5081 }
5082
5083 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
5084 self.worktree_store.read(cx).worktree_metadata_protos(cx)
5085 }
5086
5087 /// Iterator of all open buffers that have unsaved changes
5088 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
5089 self.buffer_store.read(cx).buffers().filter_map(|buf| {
5090 let buf = buf.read(cx);
5091 if buf.is_dirty() {
5092 buf.project_path(cx)
5093 } else {
5094 None
5095 }
5096 })
5097 }
5098
5099 fn set_worktrees_from_proto(
5100 &mut self,
5101 worktrees: Vec<proto::WorktreeMetadata>,
5102 cx: &mut Context<Project>,
5103 ) -> Result<()> {
5104 self.worktree_store.update(cx, |worktree_store, cx| {
5105 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
5106 })
5107 }
5108
5109 fn set_collaborators_from_proto(
5110 &mut self,
5111 messages: Vec<proto::Collaborator>,
5112 cx: &mut Context<Self>,
5113 ) -> Result<()> {
5114 let mut collaborators = HashMap::default();
5115 for message in messages {
5116 let collaborator = Collaborator::from_proto(message)?;
5117 collaborators.insert(collaborator.peer_id, collaborator);
5118 }
5119 for old_peer_id in self.collaborators.keys() {
5120 if !collaborators.contains_key(old_peer_id) {
5121 cx.emit(Event::CollaboratorLeft(*old_peer_id));
5122 }
5123 }
5124 self.collaborators = collaborators;
5125 Ok(())
5126 }
5127
5128 pub fn supplementary_language_servers<'a>(
5129 &'a self,
5130 cx: &'a App,
5131 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
5132 self.lsp_store.read(cx).supplementary_language_servers()
5133 }
5134
5135 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
5136 let Some(language) = buffer.language().cloned() else {
5137 return false;
5138 };
5139 self.lsp_store.update(cx, |lsp_store, _| {
5140 let relevant_language_servers = lsp_store
5141 .languages
5142 .lsp_adapters(&language.name())
5143 .into_iter()
5144 .map(|lsp_adapter| lsp_adapter.name())
5145 .collect::<HashSet<_>>();
5146 lsp_store
5147 .language_server_statuses()
5148 .filter_map(|(server_id, server_status)| {
5149 relevant_language_servers
5150 .contains(&server_status.name)
5151 .then_some(server_id)
5152 })
5153 .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5154 .any(InlayHints::check_capabilities)
5155 })
5156 }
5157
5158 pub fn language_server_id_for_name(
5159 &self,
5160 buffer: &Buffer,
5161 name: &LanguageServerName,
5162 cx: &App,
5163 ) -> Option<LanguageServerId> {
5164 let language = buffer.language()?;
5165 let relevant_language_servers = self
5166 .languages
5167 .lsp_adapters(&language.name())
5168 .into_iter()
5169 .map(|lsp_adapter| lsp_adapter.name())
5170 .collect::<HashSet<_>>();
5171 if !relevant_language_servers.contains(name) {
5172 return None;
5173 }
5174 self.language_server_statuses(cx)
5175 .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
5176 .find_map(|(server_id, server_status)| {
5177 if &server_status.name == name {
5178 Some(server_id)
5179 } else {
5180 None
5181 }
5182 })
5183 }
5184
5185 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
5186 self.lsp_store.update(cx, |this, cx| {
5187 this.language_servers_for_local_buffer(buffer, cx)
5188 .next()
5189 .is_some()
5190 })
5191 }
5192
5193 pub fn git_init(
5194 &self,
5195 path: Arc<Path>,
5196 fallback_branch_name: String,
5197 cx: &App,
5198 ) -> Task<Result<()>> {
5199 self.git_store
5200 .read(cx)
5201 .git_init(path, fallback_branch_name, cx)
5202 }
5203
5204 pub fn buffer_store(&self) -> &Entity<BufferStore> {
5205 &self.buffer_store
5206 }
5207
5208 pub fn git_store(&self) -> &Entity<GitStore> {
5209 &self.git_store
5210 }
5211
5212 pub fn agent_server_store(&self) -> &Entity<AgentServerStore> {
5213 &self.agent_server_store
5214 }
5215
5216 #[cfg(test)]
5217 fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
5218 cx.spawn(async move |this, cx| {
5219 let scans_complete = this
5220 .read_with(cx, |this, cx| {
5221 this.worktrees(cx)
5222 .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
5223 .collect::<Vec<_>>()
5224 })
5225 .unwrap();
5226 join_all(scans_complete).await;
5227 let barriers = this
5228 .update(cx, |this, cx| {
5229 let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
5230 repos
5231 .into_iter()
5232 .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
5233 .collect::<Vec<_>>()
5234 })
5235 .unwrap();
5236 join_all(barriers).await;
5237 })
5238 }
5239
5240 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
5241 self.git_store.read(cx).active_repository()
5242 }
5243
5244 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
5245 self.git_store.read(cx).repositories()
5246 }
5247
5248 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
5249 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
5250 }
5251
5252 pub fn set_agent_location(
5253 &mut self,
5254 new_location: Option<AgentLocation>,
5255 cx: &mut Context<Self>,
5256 ) {
5257 if let Some(old_location) = self.agent_location.as_ref() {
5258 old_location
5259 .buffer
5260 .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
5261 .ok();
5262 }
5263
5264 if let Some(location) = new_location.as_ref() {
5265 location
5266 .buffer
5267 .update(cx, |buffer, cx| {
5268 buffer.set_agent_selections(
5269 Arc::from([language::Selection {
5270 id: 0,
5271 start: location.position,
5272 end: location.position,
5273 reversed: false,
5274 goal: language::SelectionGoal::None,
5275 }]),
5276 false,
5277 CursorShape::Hollow,
5278 cx,
5279 )
5280 })
5281 .ok();
5282 }
5283
5284 self.agent_location = new_location;
5285 cx.emit(Event::AgentLocationChanged);
5286 }
5287
5288 pub fn agent_location(&self) -> Option<AgentLocation> {
5289 self.agent_location.clone()
5290 }
5291
5292 pub fn path_style(&self, cx: &App) -> PathStyle {
5293 self.worktree_store.read(cx).path_style()
5294 }
5295}
5296
5297pub struct PathMatchCandidateSet {
5298 pub snapshot: Snapshot,
5299 pub include_ignored: bool,
5300 pub include_root_name: bool,
5301 pub candidates: Candidates,
5302}
5303
5304pub enum Candidates {
5305 /// Only consider directories.
5306 Directories,
5307 /// Only consider files.
5308 Files,
5309 /// Consider directories and files.
5310 Entries,
5311}
5312
5313impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5314 type Candidates = PathMatchCandidateSetIter<'a>;
5315
5316 fn id(&self) -> usize {
5317 self.snapshot.id().to_usize()
5318 }
5319
5320 fn len(&self) -> usize {
5321 match self.candidates {
5322 Candidates::Files => {
5323 if self.include_ignored {
5324 self.snapshot.file_count()
5325 } else {
5326 self.snapshot.visible_file_count()
5327 }
5328 }
5329
5330 Candidates::Directories => {
5331 if self.include_ignored {
5332 self.snapshot.dir_count()
5333 } else {
5334 self.snapshot.visible_dir_count()
5335 }
5336 }
5337
5338 Candidates::Entries => {
5339 if self.include_ignored {
5340 self.snapshot.entry_count()
5341 } else {
5342 self.snapshot.visible_entry_count()
5343 }
5344 }
5345 }
5346 }
5347
5348 fn prefix(&self) -> Arc<RelPath> {
5349 if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
5350 self.snapshot.root_name().into()
5351 } else {
5352 RelPath::empty().into()
5353 }
5354 }
5355
5356 fn root_is_file(&self) -> bool {
5357 self.snapshot.root_entry().is_some_and(|f| f.is_file())
5358 }
5359
5360 fn path_style(&self) -> PathStyle {
5361 self.snapshot.path_style()
5362 }
5363
5364 fn candidates(&'a self, start: usize) -> Self::Candidates {
5365 PathMatchCandidateSetIter {
5366 traversal: match self.candidates {
5367 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5368 Candidates::Files => self.snapshot.files(self.include_ignored, start),
5369 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5370 },
5371 }
5372 }
5373}
5374
5375pub struct PathMatchCandidateSetIter<'a> {
5376 traversal: Traversal<'a>,
5377}
5378
5379impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5380 type Item = fuzzy::PathMatchCandidate<'a>;
5381
5382 fn next(&mut self) -> Option<Self::Item> {
5383 self.traversal
5384 .next()
5385 .map(|entry| fuzzy::PathMatchCandidate {
5386 is_dir: entry.kind.is_dir(),
5387 path: &entry.path,
5388 char_bag: entry.char_bag,
5389 })
5390 }
5391}
5392
5393impl EventEmitter<Event> for Project {}
5394
5395impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5396 fn from(val: &'a ProjectPath) -> Self {
5397 SettingsLocation {
5398 worktree_id: val.worktree_id,
5399 path: val.path.as_ref(),
5400 }
5401 }
5402}
5403
5404impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
5405 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5406 Self {
5407 worktree_id,
5408 path: path.into(),
5409 }
5410 }
5411}
5412
5413/// ResolvedPath is a path that has been resolved to either a ProjectPath
5414/// or an AbsPath and that *exists*.
5415#[derive(Debug, Clone)]
5416pub enum ResolvedPath {
5417 ProjectPath {
5418 project_path: ProjectPath,
5419 is_dir: bool,
5420 },
5421 AbsPath {
5422 path: String,
5423 is_dir: bool,
5424 },
5425}
5426
5427impl ResolvedPath {
5428 pub fn abs_path(&self) -> Option<&str> {
5429 match self {
5430 Self::AbsPath { path, .. } => Some(path),
5431 _ => None,
5432 }
5433 }
5434
5435 pub fn into_abs_path(self) -> Option<String> {
5436 match self {
5437 Self::AbsPath { path, .. } => Some(path),
5438 _ => None,
5439 }
5440 }
5441
5442 pub fn project_path(&self) -> Option<&ProjectPath> {
5443 match self {
5444 Self::ProjectPath { project_path, .. } => Some(project_path),
5445 _ => None,
5446 }
5447 }
5448
5449 pub fn is_file(&self) -> bool {
5450 !self.is_dir()
5451 }
5452
5453 pub fn is_dir(&self) -> bool {
5454 match self {
5455 Self::ProjectPath { is_dir, .. } => *is_dir,
5456 Self::AbsPath { is_dir, .. } => *is_dir,
5457 }
5458 }
5459}
5460
5461impl ProjectItem for Buffer {
5462 fn try_open(
5463 project: &Entity<Project>,
5464 path: &ProjectPath,
5465 cx: &mut App,
5466 ) -> Option<Task<Result<Entity<Self>>>> {
5467 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5468 }
5469
5470 fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
5471 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5472 }
5473
5474 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5475 self.file().map(|file| ProjectPath {
5476 worktree_id: file.worktree_id(cx),
5477 path: file.path().clone(),
5478 })
5479 }
5480
5481 fn is_dirty(&self) -> bool {
5482 self.is_dirty()
5483 }
5484}
5485
5486impl Completion {
5487 pub fn kind(&self) -> Option<CompletionItemKind> {
5488 self.source
5489 // `lsp::CompletionListItemDefaults` has no `kind` field
5490 .lsp_completion(false)
5491 .and_then(|lsp_completion| lsp_completion.kind)
5492 }
5493
5494 pub fn label(&self) -> Option<String> {
5495 self.source
5496 .lsp_completion(false)
5497 .map(|lsp_completion| lsp_completion.label.clone())
5498 }
5499
5500 /// A key that can be used to sort completions when displaying
5501 /// them to the user.
5502 pub fn sort_key(&self) -> (usize, &str) {
5503 const DEFAULT_KIND_KEY: usize = 4;
5504 let kind_key = self
5505 .kind()
5506 .and_then(|lsp_completion_kind| match lsp_completion_kind {
5507 lsp::CompletionItemKind::KEYWORD => Some(0),
5508 lsp::CompletionItemKind::VARIABLE => Some(1),
5509 lsp::CompletionItemKind::CONSTANT => Some(2),
5510 lsp::CompletionItemKind::PROPERTY => Some(3),
5511 _ => None,
5512 })
5513 .unwrap_or(DEFAULT_KIND_KEY);
5514 (kind_key, self.label.filter_text())
5515 }
5516
5517 /// Whether this completion is a snippet.
5518 pub fn is_snippet(&self) -> bool {
5519 self.source
5520 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5521 .lsp_completion(true)
5522 .is_some_and(|lsp_completion| {
5523 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5524 })
5525 }
5526
5527 /// Returns the corresponding color for this completion.
5528 ///
5529 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5530 pub fn color(&self) -> Option<Hsla> {
5531 // `lsp::CompletionListItemDefaults` has no `kind` field
5532 let lsp_completion = self.source.lsp_completion(false)?;
5533 if lsp_completion.kind? == CompletionItemKind::COLOR {
5534 return color_extractor::extract_color(&lsp_completion);
5535 }
5536 None
5537 }
5538}
5539
5540pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
5541 entries.sort_by(|entry_a, entry_b| {
5542 let entry_a = entry_a.as_ref();
5543 let entry_b = entry_b.as_ref();
5544 compare_paths(
5545 (entry_a.path.as_std_path(), entry_a.is_file()),
5546 (entry_b.path.as_std_path(), entry_b.is_file()),
5547 )
5548 });
5549}
5550
5551fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5552 match level {
5553 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5554 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5555 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5556 }
5557}
5558
5559fn provide_inline_values(
5560 captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
5561 snapshot: &language::BufferSnapshot,
5562 max_row: usize,
5563) -> Vec<InlineValueLocation> {
5564 let mut variables = Vec::new();
5565 let mut variable_position = HashSet::default();
5566 let mut scopes = Vec::new();
5567
5568 let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
5569
5570 for (capture_range, capture_kind) in captures {
5571 match capture_kind {
5572 language::DebuggerTextObject::Variable => {
5573 let variable_name = snapshot
5574 .text_for_range(capture_range.clone())
5575 .collect::<String>();
5576 let point = snapshot.offset_to_point(capture_range.end);
5577
5578 while scopes
5579 .last()
5580 .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
5581 {
5582 scopes.pop();
5583 }
5584
5585 if point.row as usize > max_row {
5586 break;
5587 }
5588
5589 let scope = if scopes
5590 .last()
5591 .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
5592 {
5593 VariableScope::Global
5594 } else {
5595 VariableScope::Local
5596 };
5597
5598 if variable_position.insert(capture_range.end) {
5599 variables.push(InlineValueLocation {
5600 variable_name,
5601 scope,
5602 lookup: VariableLookupKind::Variable,
5603 row: point.row as usize,
5604 column: point.column as usize,
5605 });
5606 }
5607 }
5608 language::DebuggerTextObject::Scope => {
5609 while scopes.last().map_or_else(
5610 || false,
5611 |scope: &Range<usize>| {
5612 !(scope.contains(&capture_range.start)
5613 && scope.contains(&capture_range.end))
5614 },
5615 ) {
5616 scopes.pop();
5617 }
5618 scopes.push(capture_range);
5619 }
5620 }
5621 }
5622
5623 variables
5624}
5625
5626#[cfg(test)]
5627mod disable_ai_settings_tests {
5628 use super::*;
5629 use gpui::TestAppContext;
5630 use settings::Settings;
5631
5632 #[gpui::test]
5633 async fn test_disable_ai_settings_security(cx: &mut TestAppContext) {
5634 cx.update(|cx| {
5635 settings::init(cx);
5636 Project::init_settings(cx);
5637
5638 // Test 1: Default is false (AI enabled)
5639 assert!(
5640 !DisableAiSettings::get_global(cx).disable_ai,
5641 "Default should allow AI"
5642 );
5643 });
5644
5645 let disable_true = serde_json::json!({
5646 "disable_ai": true
5647 })
5648 .to_string();
5649 let disable_false = serde_json::json!({
5650 "disable_ai": false
5651 })
5652 .to_string();
5653
5654 cx.update_global::<SettingsStore, _>(|store, cx| {
5655 store.set_user_settings(&disable_false, cx).unwrap();
5656 store.set_global_settings(&disable_true, cx).unwrap();
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 cx.update_global::<SettingsStore, _>(|store, cx| {
5666 store.set_global_settings(&disable_false, cx).unwrap();
5667 store.set_user_settings(&disable_true, cx).unwrap();
5668 });
5669
5670 cx.update(|cx| {
5671 assert!(
5672 DisableAiSettings::get_global(cx).disable_ai,
5673 "Local false cannot override global true"
5674 );
5675 });
5676 }
5677}