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