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