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