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