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