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