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