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 match event {
2889 DapStoreEvent::Notification(message) => {
2890 cx.emit(Event::Toast {
2891 notification_id: "dap".into(),
2892 message: message.clone(),
2893 });
2894 }
2895 _ => {}
2896 }
2897 }
2898
2899 fn on_lsp_store_event(
2900 &mut self,
2901 _: Entity<LspStore>,
2902 event: &LspStoreEvent,
2903 cx: &mut Context<Self>,
2904 ) {
2905 match event {
2906 LspStoreEvent::DiagnosticsUpdated { server_id, paths } => {
2907 cx.emit(Event::DiagnosticsUpdated {
2908 paths: paths.clone(),
2909 language_server_id: *server_id,
2910 })
2911 }
2912 LspStoreEvent::LanguageServerAdded(server_id, name, worktree_id) => cx.emit(
2913 Event::LanguageServerAdded(*server_id, name.clone(), *worktree_id),
2914 ),
2915 LspStoreEvent::LanguageServerRemoved(server_id) => {
2916 cx.emit(Event::LanguageServerRemoved(*server_id))
2917 }
2918 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2919 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2920 ),
2921 LspStoreEvent::LanguageDetected {
2922 buffer,
2923 new_language,
2924 } => {
2925 let Some(_) = new_language else {
2926 cx.emit(Event::LanguageNotFound(buffer.clone()));
2927 return;
2928 };
2929 }
2930 LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2931 LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
2932 LspStoreEvent::LanguageServerPrompt(prompt) => {
2933 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2934 }
2935 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2936 cx.emit(Event::DiskBasedDiagnosticsStarted {
2937 language_server_id: *language_server_id,
2938 });
2939 }
2940 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2941 cx.emit(Event::DiskBasedDiagnosticsFinished {
2942 language_server_id: *language_server_id,
2943 });
2944 }
2945 LspStoreEvent::LanguageServerUpdate {
2946 language_server_id,
2947 name,
2948 message,
2949 } => {
2950 if self.is_local() {
2951 self.enqueue_buffer_ordered_message(
2952 BufferOrderedMessage::LanguageServerUpdate {
2953 language_server_id: *language_server_id,
2954 message: message.clone(),
2955 name: name.clone(),
2956 },
2957 )
2958 .ok();
2959 }
2960
2961 match message {
2962 proto::update_language_server::Variant::MetadataUpdated(update) => {
2963 if let Some(capabilities) = update
2964 .capabilities
2965 .as_ref()
2966 .and_then(|capabilities| serde_json::from_str(capabilities).ok())
2967 {
2968 self.lsp_store.update(cx, |lsp_store, _| {
2969 lsp_store
2970 .lsp_server_capabilities
2971 .insert(*language_server_id, capabilities);
2972 });
2973 }
2974 }
2975 proto::update_language_server::Variant::RegisteredForBuffer(update) => {
2976 if let Some(buffer_id) = BufferId::new(update.buffer_id).ok() {
2977 cx.emit(Event::LanguageServerBufferRegistered {
2978 buffer_id,
2979 server_id: *language_server_id,
2980 buffer_abs_path: PathBuf::from(&update.buffer_abs_path),
2981 });
2982 }
2983 }
2984 _ => (),
2985 }
2986 }
2987 LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2988 notification_id: "lsp".into(),
2989 message: message.clone(),
2990 }),
2991 LspStoreEvent::SnippetEdit {
2992 buffer_id,
2993 edits,
2994 most_recent_edit,
2995 } => {
2996 if most_recent_edit.replica_id == self.replica_id() {
2997 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2998 }
2999 }
3000 }
3001 }
3002
3003 fn on_ssh_event(
3004 &mut self,
3005 _: Entity<SshRemoteClient>,
3006 event: &remote::SshRemoteEvent,
3007 cx: &mut Context<Self>,
3008 ) {
3009 match event {
3010 remote::SshRemoteEvent::Disconnected => {
3011 // if self.is_via_ssh() {
3012 // self.collaborators.clear();
3013 self.worktree_store.update(cx, |store, cx| {
3014 store.disconnected_from_host(cx);
3015 });
3016 self.buffer_store.update(cx, |buffer_store, cx| {
3017 buffer_store.disconnected_from_host(cx)
3018 });
3019 self.lsp_store.update(cx, |lsp_store, _cx| {
3020 lsp_store.disconnected_from_ssh_remote()
3021 });
3022 cx.emit(Event::DisconnectedFromSshRemote);
3023 }
3024 }
3025 }
3026
3027 fn on_settings_observer_event(
3028 &mut self,
3029 _: Entity<SettingsObserver>,
3030 event: &SettingsObserverEvent,
3031 cx: &mut Context<Self>,
3032 ) {
3033 match event {
3034 SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
3035 Err(InvalidSettingsError::LocalSettings { message, path }) => {
3036 let message = format!("Failed to set local settings in {path:?}:\n{message}");
3037 cx.emit(Event::Toast {
3038 notification_id: format!("local-settings-{path:?}").into(),
3039 message,
3040 });
3041 }
3042 Ok(path) => cx.emit(Event::HideToast {
3043 notification_id: format!("local-settings-{path:?}").into(),
3044 }),
3045 Err(_) => {}
3046 },
3047 SettingsObserverEvent::LocalTasksUpdated(result) => match result {
3048 Err(InvalidSettingsError::Tasks { message, path }) => {
3049 let message = format!("Failed to set local tasks in {path:?}:\n{message}");
3050 cx.emit(Event::Toast {
3051 notification_id: format!("local-tasks-{path:?}").into(),
3052 message,
3053 });
3054 }
3055 Ok(path) => cx.emit(Event::HideToast {
3056 notification_id: format!("local-tasks-{path:?}").into(),
3057 }),
3058 Err(_) => {}
3059 },
3060 SettingsObserverEvent::LocalDebugScenariosUpdated(result) => match result {
3061 Err(InvalidSettingsError::Debug { message, path }) => {
3062 let message =
3063 format!("Failed to set local debug scenarios in {path:?}:\n{message}");
3064 cx.emit(Event::Toast {
3065 notification_id: format!("local-debug-scenarios-{path:?}").into(),
3066 message,
3067 });
3068 }
3069 Ok(path) => cx.emit(Event::HideToast {
3070 notification_id: format!("local-debug-scenarios-{path:?}").into(),
3071 }),
3072 Err(_) => {}
3073 },
3074 }
3075 }
3076
3077 fn on_worktree_store_event(
3078 &mut self,
3079 _: Entity<WorktreeStore>,
3080 event: &WorktreeStoreEvent,
3081 cx: &mut Context<Self>,
3082 ) {
3083 match event {
3084 WorktreeStoreEvent::WorktreeAdded(worktree) => {
3085 self.on_worktree_added(worktree, cx);
3086 cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
3087 }
3088 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
3089 cx.emit(Event::WorktreeRemoved(*id));
3090 }
3091 WorktreeStoreEvent::WorktreeReleased(_, id) => {
3092 self.on_worktree_released(*id, cx);
3093 }
3094 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
3095 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
3096 WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
3097 self.client()
3098 .telemetry()
3099 .report_discovered_project_type_events(*worktree_id, changes);
3100 cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
3101 }
3102 WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
3103 cx.emit(Event::DeletedEntry(*worktree_id, *id))
3104 }
3105 // Listen to the GitStore instead.
3106 WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
3107 }
3108 }
3109
3110 fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
3111 let mut remotely_created_models = self.remotely_created_models.lock();
3112 if remotely_created_models.retain_count > 0 {
3113 remotely_created_models.worktrees.push(worktree.clone())
3114 }
3115 }
3116
3117 fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3118 if let Some(ssh) = &self.ssh_client {
3119 ssh.read(cx)
3120 .proto_client()
3121 .send(proto::RemoveWorktree {
3122 worktree_id: id_to_remove.to_proto(),
3123 })
3124 .log_err();
3125 }
3126 }
3127
3128 fn on_buffer_event(
3129 &mut self,
3130 buffer: Entity<Buffer>,
3131 event: &BufferEvent,
3132 cx: &mut Context<Self>,
3133 ) -> Option<()> {
3134 if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
3135 self.request_buffer_diff_recalculation(&buffer, cx);
3136 }
3137
3138 let buffer_id = buffer.read(cx).remote_id();
3139 match event {
3140 BufferEvent::ReloadNeeded => {
3141 if !self.is_via_collab() {
3142 self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
3143 .detach_and_log_err(cx);
3144 }
3145 }
3146 BufferEvent::Operation {
3147 operation,
3148 is_local: true,
3149 } => {
3150 let operation = language::proto::serialize_operation(operation);
3151
3152 if let Some(ssh) = &self.ssh_client {
3153 ssh.read(cx)
3154 .proto_client()
3155 .send(proto::UpdateBuffer {
3156 project_id: 0,
3157 buffer_id: buffer_id.to_proto(),
3158 operations: vec![operation.clone()],
3159 })
3160 .ok();
3161 }
3162
3163 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
3164 buffer_id,
3165 operation,
3166 })
3167 .ok();
3168 }
3169
3170 _ => {}
3171 }
3172
3173 None
3174 }
3175
3176 fn on_image_event(
3177 &mut self,
3178 image: Entity<ImageItem>,
3179 event: &ImageItemEvent,
3180 cx: &mut Context<Self>,
3181 ) -> Option<()> {
3182 match event {
3183 ImageItemEvent::ReloadNeeded => {
3184 if !self.is_via_collab() {
3185 self.reload_images([image.clone()].into_iter().collect(), cx)
3186 .detach_and_log_err(cx);
3187 }
3188 }
3189 _ => {}
3190 }
3191
3192 None
3193 }
3194
3195 fn request_buffer_diff_recalculation(
3196 &mut self,
3197 buffer: &Entity<Buffer>,
3198 cx: &mut Context<Self>,
3199 ) {
3200 self.buffers_needing_diff.insert(buffer.downgrade());
3201 let first_insertion = self.buffers_needing_diff.len() == 1;
3202
3203 let settings = ProjectSettings::get_global(cx);
3204 let delay = if let Some(delay) = settings.git.gutter_debounce {
3205 delay
3206 } else {
3207 if first_insertion {
3208 let this = cx.weak_entity();
3209 cx.defer(move |cx| {
3210 if let Some(this) = this.upgrade() {
3211 this.update(cx, |this, cx| {
3212 this.recalculate_buffer_diffs(cx).detach();
3213 });
3214 }
3215 });
3216 }
3217 return;
3218 };
3219
3220 const MIN_DELAY: u64 = 50;
3221 let delay = delay.max(MIN_DELAY);
3222 let duration = Duration::from_millis(delay);
3223
3224 self.git_diff_debouncer
3225 .fire_new(duration, cx, move |this, cx| {
3226 this.recalculate_buffer_diffs(cx)
3227 });
3228 }
3229
3230 fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
3231 cx.spawn(async move |this, cx| {
3232 loop {
3233 let task = this
3234 .update(cx, |this, cx| {
3235 let buffers = this
3236 .buffers_needing_diff
3237 .drain()
3238 .filter_map(|buffer| buffer.upgrade())
3239 .collect::<Vec<_>>();
3240 if buffers.is_empty() {
3241 None
3242 } else {
3243 Some(this.git_store.update(cx, |git_store, cx| {
3244 git_store.recalculate_buffer_diffs(buffers, cx)
3245 }))
3246 }
3247 })
3248 .ok()
3249 .flatten();
3250
3251 if let Some(task) = task {
3252 task.await;
3253 } else {
3254 break;
3255 }
3256 }
3257 })
3258 }
3259
3260 pub fn set_language_for_buffer(
3261 &mut self,
3262 buffer: &Entity<Buffer>,
3263 new_language: Arc<Language>,
3264 cx: &mut Context<Self>,
3265 ) {
3266 self.lsp_store.update(cx, |lsp_store, cx| {
3267 lsp_store.set_language_for_buffer(buffer, new_language, cx)
3268 })
3269 }
3270
3271 pub fn restart_language_servers_for_buffers(
3272 &mut self,
3273 buffers: Vec<Entity<Buffer>>,
3274 only_restart_servers: HashSet<LanguageServerSelector>,
3275 cx: &mut Context<Self>,
3276 ) {
3277 self.lsp_store.update(cx, |lsp_store, cx| {
3278 lsp_store.restart_language_servers_for_buffers(buffers, only_restart_servers, cx)
3279 })
3280 }
3281
3282 pub fn stop_language_servers_for_buffers(
3283 &mut self,
3284 buffers: Vec<Entity<Buffer>>,
3285 also_restart_servers: HashSet<LanguageServerSelector>,
3286 cx: &mut Context<Self>,
3287 ) {
3288 self.lsp_store
3289 .update(cx, |lsp_store, cx| {
3290 lsp_store.stop_language_servers_for_buffers(buffers, also_restart_servers, cx)
3291 })
3292 .detach_and_log_err(cx);
3293 }
3294
3295 pub fn cancel_language_server_work_for_buffers(
3296 &mut self,
3297 buffers: impl IntoIterator<Item = Entity<Buffer>>,
3298 cx: &mut Context<Self>,
3299 ) {
3300 self.lsp_store.update(cx, |lsp_store, cx| {
3301 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3302 })
3303 }
3304
3305 pub fn cancel_language_server_work(
3306 &mut self,
3307 server_id: LanguageServerId,
3308 token_to_cancel: Option<String>,
3309 cx: &mut Context<Self>,
3310 ) {
3311 self.lsp_store.update(cx, |lsp_store, cx| {
3312 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3313 })
3314 }
3315
3316 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3317 self.buffer_ordered_messages_tx
3318 .unbounded_send(message)
3319 .map_err(|e| anyhow!(e))
3320 }
3321
3322 pub fn available_toolchains(
3323 &self,
3324 path: ProjectPath,
3325 language_name: LanguageName,
3326 cx: &App,
3327 ) -> Task<Option<(ToolchainList, Arc<Path>)>> {
3328 if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3329 cx.spawn(async move |cx| {
3330 toolchain_store
3331 .update(cx, |this, cx| this.list_toolchains(path, language_name, cx))
3332 .ok()?
3333 .await
3334 })
3335 } else {
3336 Task::ready(None)
3337 }
3338 }
3339
3340 pub async fn toolchain_term(
3341 languages: Arc<LanguageRegistry>,
3342 language_name: LanguageName,
3343 ) -> Option<SharedString> {
3344 languages
3345 .language_for_name(language_name.as_ref())
3346 .await
3347 .ok()?
3348 .toolchain_lister()
3349 .map(|lister| lister.term())
3350 }
3351
3352 pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
3353 self.toolchain_store.clone()
3354 }
3355 pub fn activate_toolchain(
3356 &self,
3357 path: ProjectPath,
3358 toolchain: Toolchain,
3359 cx: &mut App,
3360 ) -> Task<Option<()>> {
3361 let Some(toolchain_store) = self.toolchain_store.clone() else {
3362 return Task::ready(None);
3363 };
3364 toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3365 }
3366 pub fn active_toolchain(
3367 &self,
3368 path: ProjectPath,
3369 language_name: LanguageName,
3370 cx: &App,
3371 ) -> Task<Option<Toolchain>> {
3372 let Some(toolchain_store) = self.toolchain_store.clone() else {
3373 return Task::ready(None);
3374 };
3375 toolchain_store
3376 .read(cx)
3377 .active_toolchain(path, language_name, cx)
3378 }
3379 pub fn language_server_statuses<'a>(
3380 &'a self,
3381 cx: &'a App,
3382 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3383 self.lsp_store.read(cx).language_server_statuses()
3384 }
3385
3386 pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3387 self.lsp_store.read(cx).last_formatting_failure()
3388 }
3389
3390 pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3391 self.lsp_store
3392 .update(cx, |store, _| store.reset_last_formatting_failure());
3393 }
3394
3395 pub fn reload_buffers(
3396 &self,
3397 buffers: HashSet<Entity<Buffer>>,
3398 push_to_history: bool,
3399 cx: &mut Context<Self>,
3400 ) -> Task<Result<ProjectTransaction>> {
3401 self.buffer_store.update(cx, |buffer_store, cx| {
3402 buffer_store.reload_buffers(buffers, push_to_history, cx)
3403 })
3404 }
3405
3406 pub fn reload_images(
3407 &self,
3408 images: HashSet<Entity<ImageItem>>,
3409 cx: &mut Context<Self>,
3410 ) -> Task<Result<()>> {
3411 self.image_store
3412 .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3413 }
3414
3415 pub fn format(
3416 &mut self,
3417 buffers: HashSet<Entity<Buffer>>,
3418 target: LspFormatTarget,
3419 push_to_history: bool,
3420 trigger: lsp_store::FormatTrigger,
3421 cx: &mut Context<Project>,
3422 ) -> Task<anyhow::Result<ProjectTransaction>> {
3423 self.lsp_store.update(cx, |lsp_store, cx| {
3424 lsp_store.format(buffers, target, push_to_history, trigger, cx)
3425 })
3426 }
3427
3428 pub fn definitions<T: ToPointUtf16>(
3429 &mut self,
3430 buffer: &Entity<Buffer>,
3431 position: T,
3432 cx: &mut Context<Self>,
3433 ) -> Task<Result<Vec<LocationLink>>> {
3434 let position = position.to_point_utf16(buffer.read(cx));
3435 let guard = self.retain_remotely_created_models(cx);
3436 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3437 lsp_store.definitions(buffer, position, cx)
3438 });
3439 cx.background_spawn(async move {
3440 let result = task.await;
3441 drop(guard);
3442 result
3443 })
3444 }
3445
3446 pub fn declarations<T: ToPointUtf16>(
3447 &mut self,
3448 buffer: &Entity<Buffer>,
3449 position: T,
3450 cx: &mut Context<Self>,
3451 ) -> Task<Result<Vec<LocationLink>>> {
3452 let position = position.to_point_utf16(buffer.read(cx));
3453 let guard = self.retain_remotely_created_models(cx);
3454 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3455 lsp_store.declarations(buffer, position, cx)
3456 });
3457 cx.background_spawn(async move {
3458 let result = task.await;
3459 drop(guard);
3460 result
3461 })
3462 }
3463
3464 pub fn type_definitions<T: ToPointUtf16>(
3465 &mut self,
3466 buffer: &Entity<Buffer>,
3467 position: T,
3468 cx: &mut Context<Self>,
3469 ) -> Task<Result<Vec<LocationLink>>> {
3470 let position = position.to_point_utf16(buffer.read(cx));
3471 let guard = self.retain_remotely_created_models(cx);
3472 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3473 lsp_store.type_definitions(buffer, position, cx)
3474 });
3475 cx.background_spawn(async move {
3476 let result = task.await;
3477 drop(guard);
3478 result
3479 })
3480 }
3481
3482 pub fn implementations<T: ToPointUtf16>(
3483 &mut self,
3484 buffer: &Entity<Buffer>,
3485 position: T,
3486 cx: &mut Context<Self>,
3487 ) -> Task<Result<Vec<LocationLink>>> {
3488 let position = position.to_point_utf16(buffer.read(cx));
3489 let guard = self.retain_remotely_created_models(cx);
3490 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3491 lsp_store.implementations(buffer, position, cx)
3492 });
3493 cx.background_spawn(async move {
3494 let result = task.await;
3495 drop(guard);
3496 result
3497 })
3498 }
3499
3500 pub fn references<T: ToPointUtf16>(
3501 &mut self,
3502 buffer: &Entity<Buffer>,
3503 position: T,
3504 cx: &mut Context<Self>,
3505 ) -> Task<Result<Vec<Location>>> {
3506 let position = position.to_point_utf16(buffer.read(cx));
3507 let guard = self.retain_remotely_created_models(cx);
3508 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3509 lsp_store.references(buffer, position, cx)
3510 });
3511 cx.background_spawn(async move {
3512 let result = task.await;
3513 drop(guard);
3514 result
3515 })
3516 }
3517
3518 pub fn document_highlights<T: ToPointUtf16>(
3519 &mut self,
3520 buffer: &Entity<Buffer>,
3521 position: T,
3522 cx: &mut Context<Self>,
3523 ) -> Task<Result<Vec<DocumentHighlight>>> {
3524 let position = position.to_point_utf16(buffer.read(cx));
3525 self.request_lsp(
3526 buffer.clone(),
3527 LanguageServerToQuery::FirstCapable,
3528 GetDocumentHighlights { position },
3529 cx,
3530 )
3531 }
3532
3533 pub fn document_symbols(
3534 &mut self,
3535 buffer: &Entity<Buffer>,
3536 cx: &mut Context<Self>,
3537 ) -> Task<Result<Vec<DocumentSymbol>>> {
3538 self.request_lsp(
3539 buffer.clone(),
3540 LanguageServerToQuery::FirstCapable,
3541 GetDocumentSymbols,
3542 cx,
3543 )
3544 }
3545
3546 pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3547 self.lsp_store
3548 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3549 }
3550
3551 pub fn open_buffer_for_symbol(
3552 &mut self,
3553 symbol: &Symbol,
3554 cx: &mut Context<Self>,
3555 ) -> Task<Result<Entity<Buffer>>> {
3556 self.lsp_store.update(cx, |lsp_store, cx| {
3557 lsp_store.open_buffer_for_symbol(symbol, cx)
3558 })
3559 }
3560
3561 pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3562 let guard = self.retain_remotely_created_models(cx);
3563 let Some(ssh_client) = self.ssh_client.as_ref() else {
3564 return Task::ready(Err(anyhow!("not an ssh project")));
3565 };
3566
3567 let proto_client = ssh_client.read(cx).proto_client();
3568
3569 cx.spawn(async move |project, cx| {
3570 let buffer = proto_client
3571 .request(proto::OpenServerSettings {
3572 project_id: SSH_PROJECT_ID,
3573 })
3574 .await?;
3575
3576 let buffer = project
3577 .update(cx, |project, cx| {
3578 project.buffer_store.update(cx, |buffer_store, cx| {
3579 anyhow::Ok(
3580 buffer_store
3581 .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3582 )
3583 })
3584 })??
3585 .await;
3586
3587 drop(guard);
3588 buffer
3589 })
3590 }
3591
3592 pub fn open_local_buffer_via_lsp(
3593 &mut self,
3594 abs_path: lsp::Url,
3595 language_server_id: LanguageServerId,
3596 cx: &mut Context<Self>,
3597 ) -> Task<Result<Entity<Buffer>>> {
3598 self.lsp_store.update(cx, |lsp_store, cx| {
3599 lsp_store.open_local_buffer_via_lsp(abs_path, language_server_id, cx)
3600 })
3601 }
3602
3603 pub fn signature_help<T: ToPointUtf16>(
3604 &self,
3605 buffer: &Entity<Buffer>,
3606 position: T,
3607 cx: &mut Context<Self>,
3608 ) -> Task<Vec<SignatureHelp>> {
3609 self.lsp_store.update(cx, |lsp_store, cx| {
3610 lsp_store.signature_help(buffer, position, cx)
3611 })
3612 }
3613
3614 pub fn hover<T: ToPointUtf16>(
3615 &self,
3616 buffer: &Entity<Buffer>,
3617 position: T,
3618 cx: &mut Context<Self>,
3619 ) -> Task<Vec<Hover>> {
3620 let position = position.to_point_utf16(buffer.read(cx));
3621 self.lsp_store
3622 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3623 }
3624
3625 pub fn linked_edits(
3626 &self,
3627 buffer: &Entity<Buffer>,
3628 position: Anchor,
3629 cx: &mut Context<Self>,
3630 ) -> Task<Result<Vec<Range<Anchor>>>> {
3631 self.lsp_store.update(cx, |lsp_store, cx| {
3632 lsp_store.linked_edits(buffer, position, cx)
3633 })
3634 }
3635
3636 pub fn completions<T: ToOffset + ToPointUtf16>(
3637 &self,
3638 buffer: &Entity<Buffer>,
3639 position: T,
3640 context: CompletionContext,
3641 cx: &mut Context<Self>,
3642 ) -> Task<Result<Vec<CompletionResponse>>> {
3643 let position = position.to_point_utf16(buffer.read(cx));
3644 self.lsp_store.update(cx, |lsp_store, cx| {
3645 lsp_store.completions(buffer, position, context, cx)
3646 })
3647 }
3648
3649 pub fn code_actions<T: Clone + ToOffset>(
3650 &mut self,
3651 buffer_handle: &Entity<Buffer>,
3652 range: Range<T>,
3653 kinds: Option<Vec<CodeActionKind>>,
3654 cx: &mut Context<Self>,
3655 ) -> Task<Result<Vec<CodeAction>>> {
3656 let buffer = buffer_handle.read(cx);
3657 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3658 self.lsp_store.update(cx, |lsp_store, cx| {
3659 lsp_store.code_actions(buffer_handle, range, kinds, cx)
3660 })
3661 }
3662
3663 pub fn code_lens_actions<T: Clone + ToOffset>(
3664 &mut self,
3665 buffer: &Entity<Buffer>,
3666 range: Range<T>,
3667 cx: &mut Context<Self>,
3668 ) -> Task<Result<Vec<CodeAction>>> {
3669 let snapshot = buffer.read(cx).snapshot();
3670 let range = range.clone().to_owned().to_point(&snapshot);
3671 let range_start = snapshot.anchor_before(range.start);
3672 let range_end = if range.start == range.end {
3673 range_start
3674 } else {
3675 snapshot.anchor_after(range.end)
3676 };
3677 let range = range_start..range_end;
3678 let code_lens_actions = self
3679 .lsp_store
3680 .update(cx, |lsp_store, cx| lsp_store.code_lens_actions(buffer, cx));
3681
3682 cx.background_spawn(async move {
3683 let mut code_lens_actions = code_lens_actions
3684 .await
3685 .map_err(|e| anyhow!("code lens fetch failed: {e:#}"))?;
3686 code_lens_actions.retain(|code_lens_action| {
3687 range
3688 .start
3689 .cmp(&code_lens_action.range.start, &snapshot)
3690 .is_ge()
3691 && range
3692 .end
3693 .cmp(&code_lens_action.range.end, &snapshot)
3694 .is_le()
3695 });
3696 Ok(code_lens_actions)
3697 })
3698 }
3699
3700 pub fn apply_code_action(
3701 &self,
3702 buffer_handle: Entity<Buffer>,
3703 action: CodeAction,
3704 push_to_history: bool,
3705 cx: &mut Context<Self>,
3706 ) -> Task<Result<ProjectTransaction>> {
3707 self.lsp_store.update(cx, |lsp_store, cx| {
3708 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3709 })
3710 }
3711
3712 pub fn apply_code_action_kind(
3713 &self,
3714 buffers: HashSet<Entity<Buffer>>,
3715 kind: CodeActionKind,
3716 push_to_history: bool,
3717 cx: &mut Context<Self>,
3718 ) -> Task<Result<ProjectTransaction>> {
3719 self.lsp_store.update(cx, |lsp_store, cx| {
3720 lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
3721 })
3722 }
3723
3724 pub fn prepare_rename<T: ToPointUtf16>(
3725 &mut self,
3726 buffer: Entity<Buffer>,
3727 position: T,
3728 cx: &mut Context<Self>,
3729 ) -> Task<Result<PrepareRenameResponse>> {
3730 let position = position.to_point_utf16(buffer.read(cx));
3731 self.request_lsp(
3732 buffer,
3733 LanguageServerToQuery::FirstCapable,
3734 PrepareRename { position },
3735 cx,
3736 )
3737 }
3738
3739 pub fn perform_rename<T: ToPointUtf16>(
3740 &mut self,
3741 buffer: Entity<Buffer>,
3742 position: T,
3743 new_name: String,
3744 cx: &mut Context<Self>,
3745 ) -> Task<Result<ProjectTransaction>> {
3746 let push_to_history = true;
3747 let position = position.to_point_utf16(buffer.read(cx));
3748 self.request_lsp(
3749 buffer,
3750 LanguageServerToQuery::FirstCapable,
3751 PerformRename {
3752 position,
3753 new_name,
3754 push_to_history,
3755 },
3756 cx,
3757 )
3758 }
3759
3760 pub fn on_type_format<T: ToPointUtf16>(
3761 &mut self,
3762 buffer: Entity<Buffer>,
3763 position: T,
3764 trigger: String,
3765 push_to_history: bool,
3766 cx: &mut Context<Self>,
3767 ) -> Task<Result<Option<Transaction>>> {
3768 self.lsp_store.update(cx, |lsp_store, cx| {
3769 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3770 })
3771 }
3772
3773 pub fn inline_values(
3774 &mut self,
3775 session: Entity<Session>,
3776 active_stack_frame: ActiveStackFrame,
3777 buffer_handle: Entity<Buffer>,
3778 range: Range<text::Anchor>,
3779 cx: &mut Context<Self>,
3780 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3781 let snapshot = buffer_handle.read(cx).snapshot();
3782
3783 let captures = snapshot.debug_variables_query(Anchor::MIN..range.end);
3784
3785 let row = snapshot
3786 .summary_for_anchor::<text::PointUtf16>(&range.end)
3787 .row as usize;
3788
3789 let inline_value_locations = provide_inline_values(captures, &snapshot, row);
3790
3791 let stack_frame_id = active_stack_frame.stack_frame_id;
3792 cx.spawn(async move |this, cx| {
3793 this.update(cx, |project, cx| {
3794 project.dap_store().update(cx, |dap_store, cx| {
3795 dap_store.resolve_inline_value_locations(
3796 session,
3797 stack_frame_id,
3798 buffer_handle,
3799 inline_value_locations,
3800 cx,
3801 )
3802 })
3803 })?
3804 .await
3805 })
3806 }
3807
3808 pub fn inlay_hints<T: ToOffset>(
3809 &mut self,
3810 buffer_handle: Entity<Buffer>,
3811 range: Range<T>,
3812 cx: &mut Context<Self>,
3813 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3814 let buffer = buffer_handle.read(cx);
3815 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3816 self.lsp_store.update(cx, |lsp_store, cx| {
3817 lsp_store.inlay_hints(buffer_handle, range, cx)
3818 })
3819 }
3820
3821 pub fn resolve_inlay_hint(
3822 &self,
3823 hint: InlayHint,
3824 buffer_handle: Entity<Buffer>,
3825 server_id: LanguageServerId,
3826 cx: &mut Context<Self>,
3827 ) -> Task<anyhow::Result<InlayHint>> {
3828 self.lsp_store.update(cx, |lsp_store, cx| {
3829 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3830 })
3831 }
3832
3833 pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3834 let (result_tx, result_rx) = smol::channel::unbounded();
3835
3836 let matching_buffers_rx = if query.is_opened_only() {
3837 self.sort_search_candidates(&query, cx)
3838 } else {
3839 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3840 };
3841
3842 cx.spawn(async move |_, cx| {
3843 let mut range_count = 0;
3844 let mut buffer_count = 0;
3845 let mut limit_reached = false;
3846 let query = Arc::new(query);
3847 let chunks = matching_buffers_rx.ready_chunks(64);
3848
3849 // Now that we know what paths match the query, we will load at most
3850 // 64 buffers at a time to avoid overwhelming the main thread. For each
3851 // opened buffer, we will spawn a background task that retrieves all the
3852 // ranges in the buffer matched by the query.
3853 let mut chunks = pin!(chunks);
3854 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3855 let mut chunk_results = Vec::with_capacity(matching_buffer_chunk.len());
3856 for buffer in matching_buffer_chunk {
3857 let query = query.clone();
3858 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
3859 chunk_results.push(cx.background_spawn(async move {
3860 let ranges = query
3861 .search(&snapshot, None)
3862 .await
3863 .iter()
3864 .map(|range| {
3865 snapshot.anchor_before(range.start)
3866 ..snapshot.anchor_after(range.end)
3867 })
3868 .collect::<Vec<_>>();
3869 anyhow::Ok((buffer, ranges))
3870 }));
3871 }
3872
3873 let chunk_results = futures::future::join_all(chunk_results).await;
3874 for result in chunk_results {
3875 if let Some((buffer, ranges)) = result.log_err() {
3876 range_count += ranges.len();
3877 buffer_count += 1;
3878 result_tx
3879 .send(SearchResult::Buffer { buffer, ranges })
3880 .await?;
3881 if buffer_count > MAX_SEARCH_RESULT_FILES
3882 || range_count > MAX_SEARCH_RESULT_RANGES
3883 {
3884 limit_reached = true;
3885 break 'outer;
3886 }
3887 }
3888 }
3889 }
3890
3891 if limit_reached {
3892 result_tx.send(SearchResult::LimitReached).await?;
3893 }
3894
3895 anyhow::Ok(())
3896 })
3897 .detach();
3898
3899 result_rx
3900 }
3901
3902 fn find_search_candidate_buffers(
3903 &mut self,
3904 query: &SearchQuery,
3905 limit: usize,
3906 cx: &mut Context<Project>,
3907 ) -> Receiver<Entity<Buffer>> {
3908 if self.is_local() {
3909 let fs = self.fs.clone();
3910 self.buffer_store.update(cx, |buffer_store, cx| {
3911 buffer_store.find_search_candidates(query, limit, fs, cx)
3912 })
3913 } else {
3914 self.find_search_candidates_remote(query, limit, cx)
3915 }
3916 }
3917
3918 fn sort_search_candidates(
3919 &mut self,
3920 search_query: &SearchQuery,
3921 cx: &mut Context<Project>,
3922 ) -> Receiver<Entity<Buffer>> {
3923 let worktree_store = self.worktree_store.read(cx);
3924 let mut buffers = search_query
3925 .buffers()
3926 .into_iter()
3927 .flatten()
3928 .filter(|buffer| {
3929 let b = buffer.read(cx);
3930 if let Some(file) = b.file() {
3931 if !search_query.match_path(file.path()) {
3932 return false;
3933 }
3934 if let Some(entry) = b
3935 .entry_id(cx)
3936 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3937 && entry.is_ignored
3938 && !search_query.include_ignored()
3939 {
3940 return false;
3941 }
3942 }
3943 true
3944 })
3945 .collect::<Vec<_>>();
3946 let (tx, rx) = smol::channel::unbounded();
3947 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3948 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3949 (None, Some(_)) => std::cmp::Ordering::Less,
3950 (Some(_), None) => std::cmp::Ordering::Greater,
3951 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3952 });
3953 for buffer in buffers {
3954 tx.send_blocking(buffer.clone()).unwrap()
3955 }
3956
3957 rx
3958 }
3959
3960 fn find_search_candidates_remote(
3961 &mut self,
3962 query: &SearchQuery,
3963 limit: usize,
3964 cx: &mut Context<Project>,
3965 ) -> Receiver<Entity<Buffer>> {
3966 let (tx, rx) = smol::channel::unbounded();
3967
3968 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3969 (ssh_client.read(cx).proto_client(), 0)
3970 } else if let Some(remote_id) = self.remote_id() {
3971 (self.client.clone().into(), remote_id)
3972 } else {
3973 return rx;
3974 };
3975
3976 let request = client.request(proto::FindSearchCandidates {
3977 project_id: remote_id,
3978 query: Some(query.to_proto()),
3979 limit: limit as _,
3980 });
3981 let guard = self.retain_remotely_created_models(cx);
3982
3983 cx.spawn(async move |project, cx| {
3984 let response = request.await?;
3985 for buffer_id in response.buffer_ids {
3986 let buffer_id = BufferId::new(buffer_id)?;
3987 let buffer = project
3988 .update(cx, |project, cx| {
3989 project.buffer_store.update(cx, |buffer_store, cx| {
3990 buffer_store.wait_for_remote_buffer(buffer_id, cx)
3991 })
3992 })?
3993 .await?;
3994 let _ = tx.send(buffer).await;
3995 }
3996
3997 drop(guard);
3998 anyhow::Ok(())
3999 })
4000 .detach_and_log_err(cx);
4001 rx
4002 }
4003
4004 pub fn request_lsp<R: LspCommand>(
4005 &mut self,
4006 buffer_handle: Entity<Buffer>,
4007 server: LanguageServerToQuery,
4008 request: R,
4009 cx: &mut Context<Self>,
4010 ) -> Task<Result<R::Response>>
4011 where
4012 <R::LspRequest as lsp::request::Request>::Result: Send,
4013 <R::LspRequest as lsp::request::Request>::Params: Send,
4014 {
4015 let guard = self.retain_remotely_created_models(cx);
4016 let task = self.lsp_store.update(cx, |lsp_store, cx| {
4017 lsp_store.request_lsp(buffer_handle, server, request, cx)
4018 });
4019 cx.background_spawn(async move {
4020 let result = task.await;
4021 drop(guard);
4022 result
4023 })
4024 }
4025
4026 /// Move a worktree to a new position in the worktree order.
4027 ///
4028 /// The worktree will moved to the opposite side of the destination worktree.
4029 ///
4030 /// # Example
4031 ///
4032 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4033 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4034 ///
4035 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4036 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4037 ///
4038 /// # Errors
4039 ///
4040 /// An error will be returned if the worktree or destination worktree are not found.
4041 pub fn move_worktree(
4042 &mut self,
4043 source: WorktreeId,
4044 destination: WorktreeId,
4045 cx: &mut Context<Self>,
4046 ) -> Result<()> {
4047 self.worktree_store.update(cx, |worktree_store, cx| {
4048 worktree_store.move_worktree(source, destination, cx)
4049 })
4050 }
4051
4052 pub fn find_or_create_worktree(
4053 &mut self,
4054 abs_path: impl AsRef<Path>,
4055 visible: bool,
4056 cx: &mut Context<Self>,
4057 ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
4058 self.worktree_store.update(cx, |worktree_store, cx| {
4059 worktree_store.find_or_create_worktree(abs_path, visible, cx)
4060 })
4061 }
4062
4063 pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
4064 self.worktree_store.read(cx).find_worktree(abs_path, cx)
4065 }
4066
4067 pub fn is_shared(&self) -> bool {
4068 match &self.client_state {
4069 ProjectClientState::Shared { .. } => true,
4070 ProjectClientState::Local => false,
4071 ProjectClientState::Remote { .. } => true,
4072 }
4073 }
4074
4075 /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4076 pub fn resolve_path_in_buffer(
4077 &self,
4078 path: &str,
4079 buffer: &Entity<Buffer>,
4080 cx: &mut Context<Self>,
4081 ) -> Task<Option<ResolvedPath>> {
4082 let path_buf = PathBuf::from(path);
4083 if path_buf.is_absolute() || path.starts_with("~") {
4084 self.resolve_abs_path(path, cx)
4085 } else {
4086 self.resolve_path_in_worktrees(path_buf, buffer, cx)
4087 }
4088 }
4089
4090 pub fn resolve_abs_file_path(
4091 &self,
4092 path: &str,
4093 cx: &mut Context<Self>,
4094 ) -> Task<Option<ResolvedPath>> {
4095 let resolve_task = self.resolve_abs_path(path, cx);
4096 cx.background_spawn(async move {
4097 let resolved_path = resolve_task.await;
4098 resolved_path.filter(|path| path.is_file())
4099 })
4100 }
4101
4102 pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4103 if self.is_local() {
4104 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4105 let fs = self.fs.clone();
4106 cx.background_spawn(async move {
4107 let path = expanded.as_path();
4108 let metadata = fs.metadata(path).await.ok().flatten();
4109
4110 metadata.map(|metadata| ResolvedPath::AbsPath {
4111 path: expanded,
4112 is_dir: metadata.is_dir,
4113 })
4114 })
4115 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
4116 let path_style = ssh_client.read(cx).path_style();
4117 let request_path = RemotePathBuf::from_str(path, path_style);
4118 let request = ssh_client
4119 .read(cx)
4120 .proto_client()
4121 .request(proto::GetPathMetadata {
4122 project_id: SSH_PROJECT_ID,
4123 path: request_path.to_proto(),
4124 });
4125 cx.background_spawn(async move {
4126 let response = request.await.log_err()?;
4127 if response.exists {
4128 Some(ResolvedPath::AbsPath {
4129 path: PathBuf::from_proto(response.path),
4130 is_dir: response.is_dir,
4131 })
4132 } else {
4133 None
4134 }
4135 })
4136 } else {
4137 Task::ready(None)
4138 }
4139 }
4140
4141 fn resolve_path_in_worktrees(
4142 &self,
4143 path: PathBuf,
4144 buffer: &Entity<Buffer>,
4145 cx: &mut Context<Self>,
4146 ) -> Task<Option<ResolvedPath>> {
4147 let mut candidates = vec![path.clone()];
4148
4149 if let Some(file) = buffer.read(cx).file()
4150 && let Some(dir) = file.path().parent()
4151 {
4152 let joined = dir.to_path_buf().join(path);
4153 candidates.push(joined);
4154 }
4155
4156 let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4157 let worktrees_with_ids: Vec<_> = self
4158 .worktrees(cx)
4159 .map(|worktree| {
4160 let id = worktree.read(cx).id();
4161 (worktree, id)
4162 })
4163 .collect();
4164
4165 cx.spawn(async move |_, cx| {
4166 if let Some(buffer_worktree_id) = buffer_worktree_id
4167 && let Some((worktree, _)) = worktrees_with_ids
4168 .iter()
4169 .find(|(_, id)| *id == buffer_worktree_id)
4170 {
4171 for candidate in candidates.iter() {
4172 if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4173 return Some(path);
4174 }
4175 }
4176 }
4177 for (worktree, id) in worktrees_with_ids {
4178 if Some(id) == buffer_worktree_id {
4179 continue;
4180 }
4181 for candidate in candidates.iter() {
4182 if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4183 return Some(path);
4184 }
4185 }
4186 }
4187 None
4188 })
4189 }
4190
4191 fn resolve_path_in_worktree(
4192 worktree: &Entity<Worktree>,
4193 path: &PathBuf,
4194 cx: &mut AsyncApp,
4195 ) -> Option<ResolvedPath> {
4196 worktree
4197 .read_with(cx, |worktree, _| {
4198 let root_entry_path = &worktree.root_entry()?.path;
4199 let resolved = resolve_path(root_entry_path, path);
4200 let stripped = resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
4201 worktree.entry_for_path(stripped).map(|entry| {
4202 let project_path = ProjectPath {
4203 worktree_id: worktree.id(),
4204 path: entry.path.clone(),
4205 };
4206 ResolvedPath::ProjectPath {
4207 project_path,
4208 is_dir: entry.is_dir(),
4209 }
4210 })
4211 })
4212 .ok()?
4213 }
4214
4215 pub fn list_directory(
4216 &self,
4217 query: String,
4218 cx: &mut Context<Self>,
4219 ) -> Task<Result<Vec<DirectoryItem>>> {
4220 if self.is_local() {
4221 DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4222 } else if let Some(session) = self.ssh_client.as_ref() {
4223 let path_buf = PathBuf::from(query);
4224 let request = proto::ListRemoteDirectory {
4225 dev_server_id: SSH_PROJECT_ID,
4226 path: path_buf.to_proto(),
4227 config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4228 };
4229
4230 let response = session.read(cx).proto_client().request(request);
4231 cx.background_spawn(async move {
4232 let proto::ListRemoteDirectoryResponse {
4233 entries,
4234 entry_info,
4235 } = response.await?;
4236 Ok(entries
4237 .into_iter()
4238 .zip(entry_info)
4239 .map(|(entry, info)| DirectoryItem {
4240 path: PathBuf::from(entry),
4241 is_dir: info.is_dir,
4242 })
4243 .collect())
4244 })
4245 } else {
4246 Task::ready(Err(anyhow!("cannot list directory in remote project")))
4247 }
4248 }
4249
4250 pub fn create_worktree(
4251 &mut self,
4252 abs_path: impl AsRef<Path>,
4253 visible: bool,
4254 cx: &mut Context<Self>,
4255 ) -> Task<Result<Entity<Worktree>>> {
4256 self.worktree_store.update(cx, |worktree_store, cx| {
4257 worktree_store.create_worktree(abs_path, visible, cx)
4258 })
4259 }
4260
4261 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4262 self.worktree_store.update(cx, |worktree_store, cx| {
4263 worktree_store.remove_worktree(id_to_remove, cx);
4264 });
4265 }
4266
4267 fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4268 self.worktree_store.update(cx, |worktree_store, cx| {
4269 worktree_store.add(worktree, cx);
4270 });
4271 }
4272
4273 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4274 let new_active_entry = entry.and_then(|project_path| {
4275 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4276 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4277 Some(entry.id)
4278 });
4279 if new_active_entry != self.active_entry {
4280 self.active_entry = new_active_entry;
4281 self.lsp_store.update(cx, |lsp_store, _| {
4282 lsp_store.set_active_entry(new_active_entry);
4283 });
4284 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4285 }
4286 }
4287
4288 pub fn language_servers_running_disk_based_diagnostics<'a>(
4289 &'a self,
4290 cx: &'a App,
4291 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4292 self.lsp_store
4293 .read(cx)
4294 .language_servers_running_disk_based_diagnostics()
4295 }
4296
4297 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4298 self.lsp_store
4299 .read(cx)
4300 .diagnostic_summary(include_ignored, cx)
4301 }
4302
4303 pub fn diagnostic_summaries<'a>(
4304 &'a self,
4305 include_ignored: bool,
4306 cx: &'a App,
4307 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4308 self.lsp_store
4309 .read(cx)
4310 .diagnostic_summaries(include_ignored, cx)
4311 }
4312
4313 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4314 self.active_entry
4315 }
4316
4317 pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
4318 self.worktree_store.read(cx).entry_for_path(path, cx)
4319 }
4320
4321 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4322 let worktree = self.worktree_for_entry(entry_id, cx)?;
4323 let worktree = worktree.read(cx);
4324 let worktree_id = worktree.id();
4325 let path = worktree.entry_for_id(entry_id)?.path.clone();
4326 Some(ProjectPath { worktree_id, path })
4327 }
4328
4329 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4330 self.worktree_for_id(project_path.worktree_id, cx)?
4331 .read(cx)
4332 .absolutize(&project_path.path)
4333 .ok()
4334 }
4335
4336 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4337 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4338 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4339 /// the first visible worktree that has an entry for that relative path.
4340 ///
4341 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4342 /// root name from paths.
4343 ///
4344 /// # Arguments
4345 ///
4346 /// * `path` - A full path that starts with a worktree root name, or alternatively a
4347 /// relative path within a visible worktree.
4348 /// * `cx` - A reference to the `AppContext`.
4349 ///
4350 /// # Returns
4351 ///
4352 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4353 pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4354 let path = path.as_ref();
4355 let worktree_store = self.worktree_store.read(cx);
4356
4357 if path.is_absolute() {
4358 for worktree in worktree_store.visible_worktrees(cx) {
4359 let worktree_abs_path = worktree.read(cx).abs_path();
4360
4361 if let Ok(relative_path) = path.strip_prefix(worktree_abs_path) {
4362 return Some(ProjectPath {
4363 worktree_id: worktree.read(cx).id(),
4364 path: relative_path.into(),
4365 });
4366 }
4367 }
4368 } else {
4369 for worktree in worktree_store.visible_worktrees(cx) {
4370 let worktree_root_name = worktree.read(cx).root_name();
4371 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
4372 return Some(ProjectPath {
4373 worktree_id: worktree.read(cx).id(),
4374 path: relative_path.into(),
4375 });
4376 }
4377 }
4378
4379 for worktree in worktree_store.visible_worktrees(cx) {
4380 let worktree = worktree.read(cx);
4381 if let Some(entry) = worktree.entry_for_path(path) {
4382 return Some(ProjectPath {
4383 worktree_id: worktree.id(),
4384 path: entry.path.clone(),
4385 });
4386 }
4387 }
4388 }
4389
4390 None
4391 }
4392
4393 pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4394 self.find_worktree(abs_path, cx)
4395 .map(|(worktree, relative_path)| ProjectPath {
4396 worktree_id: worktree.read(cx).id(),
4397 path: relative_path.into(),
4398 })
4399 }
4400
4401 pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4402 Some(
4403 self.worktree_for_id(project_path.worktree_id, cx)?
4404 .read(cx)
4405 .abs_path()
4406 .to_path_buf(),
4407 )
4408 }
4409
4410 pub fn blame_buffer(
4411 &self,
4412 buffer: &Entity<Buffer>,
4413 version: Option<clock::Global>,
4414 cx: &mut App,
4415 ) -> Task<Result<Option<Blame>>> {
4416 self.git_store.update(cx, |git_store, cx| {
4417 git_store.blame_buffer(buffer, version, cx)
4418 })
4419 }
4420
4421 pub fn get_permalink_to_line(
4422 &self,
4423 buffer: &Entity<Buffer>,
4424 selection: Range<u32>,
4425 cx: &mut App,
4426 ) -> Task<Result<url::Url>> {
4427 self.git_store.update(cx, |git_store, cx| {
4428 git_store.get_permalink_to_line(buffer, selection, cx)
4429 })
4430 }
4431
4432 // RPC message handlers
4433
4434 async fn handle_unshare_project(
4435 this: Entity<Self>,
4436 _: TypedEnvelope<proto::UnshareProject>,
4437 mut cx: AsyncApp,
4438 ) -> Result<()> {
4439 this.update(&mut cx, |this, cx| {
4440 if this.is_local() || this.is_via_ssh() {
4441 this.unshare(cx)?;
4442 } else {
4443 this.disconnected_from_host(cx);
4444 }
4445 Ok(())
4446 })?
4447 }
4448
4449 async fn handle_add_collaborator(
4450 this: Entity<Self>,
4451 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4452 mut cx: AsyncApp,
4453 ) -> Result<()> {
4454 let collaborator = envelope
4455 .payload
4456 .collaborator
4457 .take()
4458 .context("empty collaborator")?;
4459
4460 let collaborator = Collaborator::from_proto(collaborator)?;
4461 this.update(&mut cx, |this, cx| {
4462 this.buffer_store.update(cx, |buffer_store, _| {
4463 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4464 });
4465 this.breakpoint_store.read(cx).broadcast();
4466 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4467 this.collaborators
4468 .insert(collaborator.peer_id, collaborator);
4469 })?;
4470
4471 Ok(())
4472 }
4473
4474 async fn handle_update_project_collaborator(
4475 this: Entity<Self>,
4476 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4477 mut cx: AsyncApp,
4478 ) -> Result<()> {
4479 let old_peer_id = envelope
4480 .payload
4481 .old_peer_id
4482 .context("missing old peer id")?;
4483 let new_peer_id = envelope
4484 .payload
4485 .new_peer_id
4486 .context("missing new peer id")?;
4487 this.update(&mut cx, |this, cx| {
4488 let collaborator = this
4489 .collaborators
4490 .remove(&old_peer_id)
4491 .context("received UpdateProjectCollaborator for unknown peer")?;
4492 let is_host = collaborator.is_host;
4493 this.collaborators.insert(new_peer_id, collaborator);
4494
4495 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4496 this.buffer_store.update(cx, |buffer_store, _| {
4497 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4498 });
4499
4500 if is_host {
4501 this.buffer_store
4502 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4503 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4504 .unwrap();
4505 cx.emit(Event::HostReshared);
4506 }
4507
4508 cx.emit(Event::CollaboratorUpdated {
4509 old_peer_id,
4510 new_peer_id,
4511 });
4512 Ok(())
4513 })?
4514 }
4515
4516 async fn handle_remove_collaborator(
4517 this: Entity<Self>,
4518 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4519 mut cx: AsyncApp,
4520 ) -> Result<()> {
4521 this.update(&mut cx, |this, cx| {
4522 let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4523 let replica_id = this
4524 .collaborators
4525 .remove(&peer_id)
4526 .with_context(|| format!("unknown peer {peer_id:?}"))?
4527 .replica_id;
4528 this.buffer_store.update(cx, |buffer_store, cx| {
4529 buffer_store.forget_shared_buffers_for(&peer_id);
4530 for buffer in buffer_store.buffers() {
4531 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4532 }
4533 });
4534 this.git_store.update(cx, |git_store, _| {
4535 git_store.forget_shared_diffs_for(&peer_id);
4536 });
4537
4538 cx.emit(Event::CollaboratorLeft(peer_id));
4539 Ok(())
4540 })?
4541 }
4542
4543 async fn handle_update_project(
4544 this: Entity<Self>,
4545 envelope: TypedEnvelope<proto::UpdateProject>,
4546 mut cx: AsyncApp,
4547 ) -> Result<()> {
4548 this.update(&mut cx, |this, cx| {
4549 // Don't handle messages that were sent before the response to us joining the project
4550 if envelope.message_id > this.join_project_response_message_id {
4551 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4552 }
4553 Ok(())
4554 })?
4555 }
4556
4557 async fn handle_toast(
4558 this: Entity<Self>,
4559 envelope: TypedEnvelope<proto::Toast>,
4560 mut cx: AsyncApp,
4561 ) -> Result<()> {
4562 this.update(&mut cx, |_, cx| {
4563 cx.emit(Event::Toast {
4564 notification_id: envelope.payload.notification_id.into(),
4565 message: envelope.payload.message,
4566 });
4567 Ok(())
4568 })?
4569 }
4570
4571 async fn handle_language_server_prompt_request(
4572 this: Entity<Self>,
4573 envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4574 mut cx: AsyncApp,
4575 ) -> Result<proto::LanguageServerPromptResponse> {
4576 let (tx, rx) = smol::channel::bounded(1);
4577 let actions: Vec<_> = envelope
4578 .payload
4579 .actions
4580 .into_iter()
4581 .map(|action| MessageActionItem {
4582 title: action,
4583 properties: Default::default(),
4584 })
4585 .collect();
4586 this.update(&mut cx, |_, cx| {
4587 cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4588 level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4589 message: envelope.payload.message,
4590 actions: actions.clone(),
4591 lsp_name: envelope.payload.lsp_name,
4592 response_channel: tx,
4593 }));
4594
4595 anyhow::Ok(())
4596 })??;
4597
4598 // We drop `this` to avoid holding a reference in this future for too
4599 // long.
4600 // If we keep the reference, we might not drop the `Project` early
4601 // enough when closing a window and it will only get releases on the
4602 // next `flush_effects()` call.
4603 drop(this);
4604
4605 let mut rx = pin!(rx);
4606 let answer = rx.next().await;
4607
4608 Ok(LanguageServerPromptResponse {
4609 action_response: answer.and_then(|answer| {
4610 actions
4611 .iter()
4612 .position(|action| *action == answer)
4613 .map(|index| index as u64)
4614 }),
4615 })
4616 }
4617
4618 async fn handle_hide_toast(
4619 this: Entity<Self>,
4620 envelope: TypedEnvelope<proto::HideToast>,
4621 mut cx: AsyncApp,
4622 ) -> Result<()> {
4623 this.update(&mut cx, |_, cx| {
4624 cx.emit(Event::HideToast {
4625 notification_id: envelope.payload.notification_id.into(),
4626 });
4627 Ok(())
4628 })?
4629 }
4630
4631 // Collab sends UpdateWorktree protos as messages
4632 async fn handle_update_worktree(
4633 this: Entity<Self>,
4634 envelope: TypedEnvelope<proto::UpdateWorktree>,
4635 mut cx: AsyncApp,
4636 ) -> Result<()> {
4637 this.update(&mut cx, |this, cx| {
4638 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4639 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4640 worktree.update(cx, |worktree, _| {
4641 let worktree = worktree.as_remote_mut().unwrap();
4642 worktree.update_from_remote(envelope.payload);
4643 });
4644 }
4645 Ok(())
4646 })?
4647 }
4648
4649 async fn handle_update_buffer_from_ssh(
4650 this: Entity<Self>,
4651 envelope: TypedEnvelope<proto::UpdateBuffer>,
4652 cx: AsyncApp,
4653 ) -> Result<proto::Ack> {
4654 let buffer_store = this.read_with(&cx, |this, cx| {
4655 if let Some(remote_id) = this.remote_id() {
4656 let mut payload = envelope.payload.clone();
4657 payload.project_id = remote_id;
4658 cx.background_spawn(this.client.request(payload))
4659 .detach_and_log_err(cx);
4660 }
4661 this.buffer_store.clone()
4662 })?;
4663 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4664 }
4665
4666 async fn handle_update_buffer(
4667 this: Entity<Self>,
4668 envelope: TypedEnvelope<proto::UpdateBuffer>,
4669 cx: AsyncApp,
4670 ) -> Result<proto::Ack> {
4671 let buffer_store = this.read_with(&cx, |this, cx| {
4672 if let Some(ssh) = &this.ssh_client {
4673 let mut payload = envelope.payload.clone();
4674 payload.project_id = SSH_PROJECT_ID;
4675 cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4676 .detach_and_log_err(cx);
4677 }
4678 this.buffer_store.clone()
4679 })?;
4680 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4681 }
4682
4683 fn retain_remotely_created_models(
4684 &mut self,
4685 cx: &mut Context<Self>,
4686 ) -> RemotelyCreatedModelGuard {
4687 {
4688 let mut remotely_create_models = self.remotely_created_models.lock();
4689 if remotely_create_models.retain_count == 0 {
4690 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4691 remotely_create_models.worktrees =
4692 self.worktree_store.read(cx).worktrees().collect();
4693 }
4694 remotely_create_models.retain_count += 1;
4695 }
4696 RemotelyCreatedModelGuard {
4697 remote_models: Arc::downgrade(&self.remotely_created_models),
4698 }
4699 }
4700
4701 async fn handle_create_buffer_for_peer(
4702 this: Entity<Self>,
4703 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4704 mut cx: AsyncApp,
4705 ) -> Result<()> {
4706 this.update(&mut cx, |this, cx| {
4707 this.buffer_store.update(cx, |buffer_store, cx| {
4708 buffer_store.handle_create_buffer_for_peer(
4709 envelope,
4710 this.replica_id(),
4711 this.capability(),
4712 cx,
4713 )
4714 })
4715 })?
4716 }
4717
4718 async fn handle_synchronize_buffers(
4719 this: Entity<Self>,
4720 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4721 mut cx: AsyncApp,
4722 ) -> Result<proto::SynchronizeBuffersResponse> {
4723 let response = this.update(&mut cx, |this, cx| {
4724 let client = this.client.clone();
4725 this.buffer_store.update(cx, |this, cx| {
4726 this.handle_synchronize_buffers(envelope, cx, client)
4727 })
4728 })??;
4729
4730 Ok(response)
4731 }
4732
4733 async fn handle_search_candidate_buffers(
4734 this: Entity<Self>,
4735 envelope: TypedEnvelope<proto::FindSearchCandidates>,
4736 mut cx: AsyncApp,
4737 ) -> Result<proto::FindSearchCandidatesResponse> {
4738 let peer_id = envelope.original_sender_id()?;
4739 let message = envelope.payload;
4740 let query = SearchQuery::from_proto(message.query.context("missing query field")?)?;
4741 let results = this.update(&mut cx, |this, cx| {
4742 this.find_search_candidate_buffers(&query, message.limit as _, cx)
4743 })?;
4744
4745 let mut response = proto::FindSearchCandidatesResponse {
4746 buffer_ids: Vec::new(),
4747 };
4748
4749 while let Ok(buffer) = results.recv().await {
4750 this.update(&mut cx, |this, cx| {
4751 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4752 response.buffer_ids.push(buffer_id.to_proto());
4753 })?;
4754 }
4755
4756 Ok(response)
4757 }
4758
4759 async fn handle_open_buffer_by_id(
4760 this: Entity<Self>,
4761 envelope: TypedEnvelope<proto::OpenBufferById>,
4762 mut cx: AsyncApp,
4763 ) -> Result<proto::OpenBufferResponse> {
4764 let peer_id = envelope.original_sender_id()?;
4765 let buffer_id = BufferId::new(envelope.payload.id)?;
4766 let buffer = this
4767 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4768 .await?;
4769 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4770 }
4771
4772 async fn handle_open_buffer_by_path(
4773 this: Entity<Self>,
4774 envelope: TypedEnvelope<proto::OpenBufferByPath>,
4775 mut cx: AsyncApp,
4776 ) -> Result<proto::OpenBufferResponse> {
4777 let peer_id = envelope.original_sender_id()?;
4778 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4779 let open_buffer = this.update(&mut cx, |this, cx| {
4780 this.open_buffer(
4781 ProjectPath {
4782 worktree_id,
4783 path: Arc::<Path>::from_proto(envelope.payload.path),
4784 },
4785 cx,
4786 )
4787 })?;
4788
4789 let buffer = open_buffer.await?;
4790 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4791 }
4792
4793 async fn handle_open_new_buffer(
4794 this: Entity<Self>,
4795 envelope: TypedEnvelope<proto::OpenNewBuffer>,
4796 mut cx: AsyncApp,
4797 ) -> Result<proto::OpenBufferResponse> {
4798 let buffer = this
4799 .update(&mut cx, |this, cx| this.create_buffer(cx))?
4800 .await?;
4801 let peer_id = envelope.original_sender_id()?;
4802
4803 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4804 }
4805
4806 fn respond_to_open_buffer_request(
4807 this: Entity<Self>,
4808 buffer: Entity<Buffer>,
4809 peer_id: proto::PeerId,
4810 cx: &mut AsyncApp,
4811 ) -> Result<proto::OpenBufferResponse> {
4812 this.update(cx, |this, cx| {
4813 let is_private = buffer
4814 .read(cx)
4815 .file()
4816 .map(|f| f.is_private())
4817 .unwrap_or_default();
4818 anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
4819 Ok(proto::OpenBufferResponse {
4820 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4821 })
4822 })?
4823 }
4824
4825 fn create_buffer_for_peer(
4826 &mut self,
4827 buffer: &Entity<Buffer>,
4828 peer_id: proto::PeerId,
4829 cx: &mut App,
4830 ) -> BufferId {
4831 self.buffer_store
4832 .update(cx, |buffer_store, cx| {
4833 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4834 })
4835 .detach_and_log_err(cx);
4836 buffer.read(cx).remote_id()
4837 }
4838
4839 fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4840 let project_id = match self.client_state {
4841 ProjectClientState::Remote {
4842 sharing_has_stopped,
4843 remote_id,
4844 ..
4845 } => {
4846 if sharing_has_stopped {
4847 return Task::ready(Err(anyhow!(
4848 "can't synchronize remote buffers on a readonly project"
4849 )));
4850 } else {
4851 remote_id
4852 }
4853 }
4854 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4855 return Task::ready(Err(anyhow!(
4856 "can't synchronize remote buffers on a local project"
4857 )));
4858 }
4859 };
4860
4861 let client = self.client.clone();
4862 cx.spawn(async move |this, cx| {
4863 let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
4864 this.buffer_store.read(cx).buffer_version_info(cx)
4865 })?;
4866 let response = client
4867 .request(proto::SynchronizeBuffers {
4868 project_id,
4869 buffers,
4870 })
4871 .await?;
4872
4873 let send_updates_for_buffers = this.update(cx, |this, cx| {
4874 response
4875 .buffers
4876 .into_iter()
4877 .map(|buffer| {
4878 let client = client.clone();
4879 let buffer_id = match BufferId::new(buffer.id) {
4880 Ok(id) => id,
4881 Err(e) => {
4882 return Task::ready(Err(e));
4883 }
4884 };
4885 let remote_version = language::proto::deserialize_version(&buffer.version);
4886 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4887 let operations =
4888 buffer.read(cx).serialize_ops(Some(remote_version), cx);
4889 cx.background_spawn(async move {
4890 let operations = operations.await;
4891 for chunk in split_operations(operations) {
4892 client
4893 .request(proto::UpdateBuffer {
4894 project_id,
4895 buffer_id: buffer_id.into(),
4896 operations: chunk,
4897 })
4898 .await?;
4899 }
4900 anyhow::Ok(())
4901 })
4902 } else {
4903 Task::ready(Ok(()))
4904 }
4905 })
4906 .collect::<Vec<_>>()
4907 })?;
4908
4909 // Any incomplete buffers have open requests waiting. Request that the host sends
4910 // creates these buffers for us again to unblock any waiting futures.
4911 for id in incomplete_buffer_ids {
4912 cx.background_spawn(client.request(proto::OpenBufferById {
4913 project_id,
4914 id: id.into(),
4915 }))
4916 .detach();
4917 }
4918
4919 futures::future::join_all(send_updates_for_buffers)
4920 .await
4921 .into_iter()
4922 .collect()
4923 })
4924 }
4925
4926 pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4927 self.worktree_store.read(cx).worktree_metadata_protos(cx)
4928 }
4929
4930 /// Iterator of all open buffers that have unsaved changes
4931 pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4932 self.buffer_store.read(cx).buffers().filter_map(|buf| {
4933 let buf = buf.read(cx);
4934 if buf.is_dirty() {
4935 buf.project_path(cx)
4936 } else {
4937 None
4938 }
4939 })
4940 }
4941
4942 fn set_worktrees_from_proto(
4943 &mut self,
4944 worktrees: Vec<proto::WorktreeMetadata>,
4945 cx: &mut Context<Project>,
4946 ) -> Result<()> {
4947 self.worktree_store.update(cx, |worktree_store, cx| {
4948 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4949 })
4950 }
4951
4952 fn set_collaborators_from_proto(
4953 &mut self,
4954 messages: Vec<proto::Collaborator>,
4955 cx: &mut Context<Self>,
4956 ) -> Result<()> {
4957 let mut collaborators = HashMap::default();
4958 for message in messages {
4959 let collaborator = Collaborator::from_proto(message)?;
4960 collaborators.insert(collaborator.peer_id, collaborator);
4961 }
4962 for old_peer_id in self.collaborators.keys() {
4963 if !collaborators.contains_key(old_peer_id) {
4964 cx.emit(Event::CollaboratorLeft(*old_peer_id));
4965 }
4966 }
4967 self.collaborators = collaborators;
4968 Ok(())
4969 }
4970
4971 pub fn supplementary_language_servers<'a>(
4972 &'a self,
4973 cx: &'a App,
4974 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4975 self.lsp_store.read(cx).supplementary_language_servers()
4976 }
4977
4978 pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4979 let Some(language) = buffer.language().cloned() else {
4980 return false;
4981 };
4982 self.lsp_store.update(cx, |lsp_store, _| {
4983 let relevant_language_servers = lsp_store
4984 .languages
4985 .lsp_adapters(&language.name())
4986 .into_iter()
4987 .map(|lsp_adapter| lsp_adapter.name())
4988 .collect::<HashSet<_>>();
4989 lsp_store
4990 .language_server_statuses()
4991 .filter_map(|(server_id, server_status)| {
4992 relevant_language_servers
4993 .contains(&server_status.name)
4994 .then_some(server_id)
4995 })
4996 .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
4997 .any(InlayHints::check_capabilities)
4998 })
4999 }
5000
5001 pub fn language_server_id_for_name(
5002 &self,
5003 buffer: &Buffer,
5004 name: &LanguageServerName,
5005 cx: &App,
5006 ) -> Option<LanguageServerId> {
5007 let language = buffer.language()?;
5008 let relevant_language_servers = self
5009 .languages
5010 .lsp_adapters(&language.name())
5011 .into_iter()
5012 .map(|lsp_adapter| lsp_adapter.name())
5013 .collect::<HashSet<_>>();
5014 if !relevant_language_servers.contains(name) {
5015 return None;
5016 }
5017 self.language_server_statuses(cx)
5018 .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
5019 .find_map(|(server_id, server_status)| {
5020 if &server_status.name == name {
5021 Some(server_id)
5022 } else {
5023 None
5024 }
5025 })
5026 }
5027
5028 pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
5029 self.lsp_store.update(cx, |this, cx| {
5030 this.language_servers_for_local_buffer(buffer, cx)
5031 .next()
5032 .is_some()
5033 })
5034 }
5035
5036 pub fn git_init(
5037 &self,
5038 path: Arc<Path>,
5039 fallback_branch_name: String,
5040 cx: &App,
5041 ) -> Task<Result<()>> {
5042 self.git_store
5043 .read(cx)
5044 .git_init(path, fallback_branch_name, cx)
5045 }
5046
5047 pub fn buffer_store(&self) -> &Entity<BufferStore> {
5048 &self.buffer_store
5049 }
5050
5051 pub fn git_store(&self) -> &Entity<GitStore> {
5052 &self.git_store
5053 }
5054
5055 #[cfg(test)]
5056 fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
5057 cx.spawn(async move |this, cx| {
5058 let scans_complete = this
5059 .read_with(cx, |this, cx| {
5060 this.worktrees(cx)
5061 .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
5062 .collect::<Vec<_>>()
5063 })
5064 .unwrap();
5065 join_all(scans_complete).await;
5066 let barriers = this
5067 .update(cx, |this, cx| {
5068 let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
5069 repos
5070 .into_iter()
5071 .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
5072 .collect::<Vec<_>>()
5073 })
5074 .unwrap();
5075 join_all(barriers).await;
5076 })
5077 }
5078
5079 pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
5080 self.git_store.read(cx).active_repository()
5081 }
5082
5083 pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
5084 self.git_store.read(cx).repositories()
5085 }
5086
5087 pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
5088 self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
5089 }
5090
5091 pub fn set_agent_location(
5092 &mut self,
5093 new_location: Option<AgentLocation>,
5094 cx: &mut Context<Self>,
5095 ) {
5096 if let Some(old_location) = self.agent_location.as_ref() {
5097 old_location
5098 .buffer
5099 .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
5100 .ok();
5101 }
5102
5103 if let Some(location) = new_location.as_ref() {
5104 location
5105 .buffer
5106 .update(cx, |buffer, cx| {
5107 buffer.set_agent_selections(
5108 Arc::from([language::Selection {
5109 id: 0,
5110 start: location.position,
5111 end: location.position,
5112 reversed: false,
5113 goal: language::SelectionGoal::None,
5114 }]),
5115 false,
5116 CursorShape::Hollow,
5117 cx,
5118 )
5119 })
5120 .ok();
5121 }
5122
5123 self.agent_location = new_location;
5124 cx.emit(Event::AgentLocationChanged);
5125 }
5126
5127 pub fn agent_location(&self) -> Option<AgentLocation> {
5128 self.agent_location.clone()
5129 }
5130
5131 pub fn mark_buffer_as_non_searchable(&self, buffer_id: BufferId, cx: &mut Context<Project>) {
5132 self.buffer_store.update(cx, |buffer_store, _| {
5133 buffer_store.mark_buffer_as_non_searchable(buffer_id)
5134 });
5135 }
5136}
5137
5138pub struct PathMatchCandidateSet {
5139 pub snapshot: Snapshot,
5140 pub include_ignored: bool,
5141 pub include_root_name: bool,
5142 pub candidates: Candidates,
5143}
5144
5145pub enum Candidates {
5146 /// Only consider directories.
5147 Directories,
5148 /// Only consider files.
5149 Files,
5150 /// Consider directories and files.
5151 Entries,
5152}
5153
5154impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5155 type Candidates = PathMatchCandidateSetIter<'a>;
5156
5157 fn id(&self) -> usize {
5158 self.snapshot.id().to_usize()
5159 }
5160
5161 fn len(&self) -> usize {
5162 match self.candidates {
5163 Candidates::Files => {
5164 if self.include_ignored {
5165 self.snapshot.file_count()
5166 } else {
5167 self.snapshot.visible_file_count()
5168 }
5169 }
5170
5171 Candidates::Directories => {
5172 if self.include_ignored {
5173 self.snapshot.dir_count()
5174 } else {
5175 self.snapshot.visible_dir_count()
5176 }
5177 }
5178
5179 Candidates::Entries => {
5180 if self.include_ignored {
5181 self.snapshot.entry_count()
5182 } else {
5183 self.snapshot.visible_entry_count()
5184 }
5185 }
5186 }
5187 }
5188
5189 fn prefix(&self) -> Arc<str> {
5190 if self.snapshot.root_entry().is_some_and(|e| e.is_file()) {
5191 self.snapshot.root_name().into()
5192 } else if self.include_root_name {
5193 format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
5194 } else {
5195 Arc::default()
5196 }
5197 }
5198
5199 fn candidates(&'a self, start: usize) -> Self::Candidates {
5200 PathMatchCandidateSetIter {
5201 traversal: match self.candidates {
5202 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5203 Candidates::Files => self.snapshot.files(self.include_ignored, start),
5204 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5205 },
5206 }
5207 }
5208}
5209
5210pub struct PathMatchCandidateSetIter<'a> {
5211 traversal: Traversal<'a>,
5212}
5213
5214impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5215 type Item = fuzzy::PathMatchCandidate<'a>;
5216
5217 fn next(&mut self) -> Option<Self::Item> {
5218 self.traversal
5219 .next()
5220 .map(|entry| fuzzy::PathMatchCandidate {
5221 is_dir: entry.kind.is_dir(),
5222 path: &entry.path,
5223 char_bag: entry.char_bag,
5224 })
5225 }
5226}
5227
5228impl EventEmitter<Event> for Project {}
5229
5230impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5231 fn from(val: &'a ProjectPath) -> Self {
5232 SettingsLocation {
5233 worktree_id: val.worktree_id,
5234 path: val.path.as_ref(),
5235 }
5236 }
5237}
5238
5239impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5240 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5241 Self {
5242 worktree_id,
5243 path: path.as_ref().into(),
5244 }
5245 }
5246}
5247
5248pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5249 let mut path_components = path.components();
5250 let mut base_components = base.components();
5251 let mut components: Vec<Component> = Vec::new();
5252 loop {
5253 match (path_components.next(), base_components.next()) {
5254 (None, None) => break,
5255 (Some(a), None) => {
5256 components.push(a);
5257 components.extend(path_components.by_ref());
5258 break;
5259 }
5260 (None, _) => components.push(Component::ParentDir),
5261 (Some(a), Some(b)) if components.is_empty() && a == b => (),
5262 (Some(a), Some(Component::CurDir)) => components.push(a),
5263 (Some(a), Some(_)) => {
5264 components.push(Component::ParentDir);
5265 for _ in base_components {
5266 components.push(Component::ParentDir);
5267 }
5268 components.push(a);
5269 components.extend(path_components.by_ref());
5270 break;
5271 }
5272 }
5273 }
5274 components.iter().map(|c| c.as_os_str()).collect()
5275}
5276
5277fn resolve_path(base: &Path, path: &Path) -> PathBuf {
5278 let mut result = base.to_path_buf();
5279 for component in path.components() {
5280 match component {
5281 Component::ParentDir => {
5282 result.pop();
5283 }
5284 Component::CurDir => (),
5285 _ => result.push(component),
5286 }
5287 }
5288 result
5289}
5290
5291/// ResolvedPath is a path that has been resolved to either a ProjectPath
5292/// or an AbsPath and that *exists*.
5293#[derive(Debug, Clone)]
5294pub enum ResolvedPath {
5295 ProjectPath {
5296 project_path: ProjectPath,
5297 is_dir: bool,
5298 },
5299 AbsPath {
5300 path: PathBuf,
5301 is_dir: bool,
5302 },
5303}
5304
5305impl ResolvedPath {
5306 pub fn abs_path(&self) -> Option<&Path> {
5307 match self {
5308 Self::AbsPath { path, .. } => Some(path.as_path()),
5309 _ => None,
5310 }
5311 }
5312
5313 pub fn into_abs_path(self) -> Option<PathBuf> {
5314 match self {
5315 Self::AbsPath { path, .. } => Some(path),
5316 _ => None,
5317 }
5318 }
5319
5320 pub fn project_path(&self) -> Option<&ProjectPath> {
5321 match self {
5322 Self::ProjectPath { project_path, .. } => Some(project_path),
5323 _ => None,
5324 }
5325 }
5326
5327 pub fn is_file(&self) -> bool {
5328 !self.is_dir()
5329 }
5330
5331 pub fn is_dir(&self) -> bool {
5332 match self {
5333 Self::ProjectPath { is_dir, .. } => *is_dir,
5334 Self::AbsPath { is_dir, .. } => *is_dir,
5335 }
5336 }
5337}
5338
5339impl ProjectItem for Buffer {
5340 fn try_open(
5341 project: &Entity<Project>,
5342 path: &ProjectPath,
5343 cx: &mut App,
5344 ) -> Option<Task<Result<Entity<Self>>>> {
5345 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5346 }
5347
5348 fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
5349 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5350 }
5351
5352 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5353 self.file().map(|file| ProjectPath {
5354 worktree_id: file.worktree_id(cx),
5355 path: file.path().clone(),
5356 })
5357 }
5358
5359 fn is_dirty(&self) -> bool {
5360 self.is_dirty()
5361 }
5362}
5363
5364impl Completion {
5365 pub fn kind(&self) -> Option<CompletionItemKind> {
5366 self.source
5367 // `lsp::CompletionListItemDefaults` has no `kind` field
5368 .lsp_completion(false)
5369 .and_then(|lsp_completion| lsp_completion.kind)
5370 }
5371
5372 pub fn label(&self) -> Option<String> {
5373 self.source
5374 .lsp_completion(false)
5375 .map(|lsp_completion| lsp_completion.label.clone())
5376 }
5377
5378 /// A key that can be used to sort completions when displaying
5379 /// them to the user.
5380 pub fn sort_key(&self) -> (usize, &str) {
5381 const DEFAULT_KIND_KEY: usize = 4;
5382 let kind_key = self
5383 .kind()
5384 .and_then(|lsp_completion_kind| match lsp_completion_kind {
5385 lsp::CompletionItemKind::KEYWORD => Some(0),
5386 lsp::CompletionItemKind::VARIABLE => Some(1),
5387 lsp::CompletionItemKind::CONSTANT => Some(2),
5388 lsp::CompletionItemKind::PROPERTY => Some(3),
5389 _ => None,
5390 })
5391 .unwrap_or(DEFAULT_KIND_KEY);
5392 (kind_key, self.label.filter_text())
5393 }
5394
5395 /// Whether this completion is a snippet.
5396 pub fn is_snippet(&self) -> bool {
5397 self.source
5398 // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5399 .lsp_completion(true)
5400 .is_some_and(|lsp_completion| {
5401 lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5402 })
5403 }
5404
5405 /// Returns the corresponding color for this completion.
5406 ///
5407 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5408 pub fn color(&self) -> Option<Hsla> {
5409 // `lsp::CompletionListItemDefaults` has no `kind` field
5410 let lsp_completion = self.source.lsp_completion(false)?;
5411 if lsp_completion.kind? == CompletionItemKind::COLOR {
5412 return color_extractor::extract_color(&lsp_completion);
5413 }
5414 None
5415 }
5416}
5417
5418pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
5419 entries.sort_by(|entry_a, entry_b| {
5420 let entry_a = entry_a.as_ref();
5421 let entry_b = entry_b.as_ref();
5422 compare_paths(
5423 (&entry_a.path, entry_a.is_file()),
5424 (&entry_b.path, entry_b.is_file()),
5425 )
5426 });
5427}
5428
5429fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5430 match level {
5431 proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5432 proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5433 proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5434 }
5435}
5436
5437fn provide_inline_values(
5438 captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
5439 snapshot: &language::BufferSnapshot,
5440 max_row: usize,
5441) -> Vec<InlineValueLocation> {
5442 let mut variables = Vec::new();
5443 let mut variable_position = HashSet::default();
5444 let mut scopes = Vec::new();
5445
5446 let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
5447
5448 for (capture_range, capture_kind) in captures {
5449 match capture_kind {
5450 language::DebuggerTextObject::Variable => {
5451 let variable_name = snapshot
5452 .text_for_range(capture_range.clone())
5453 .collect::<String>();
5454 let point = snapshot.offset_to_point(capture_range.end);
5455
5456 while scopes
5457 .last()
5458 .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
5459 {
5460 scopes.pop();
5461 }
5462
5463 if point.row as usize > max_row {
5464 break;
5465 }
5466
5467 let scope = if scopes
5468 .last()
5469 .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
5470 {
5471 VariableScope::Global
5472 } else {
5473 VariableScope::Local
5474 };
5475
5476 if variable_position.insert(capture_range.end) {
5477 variables.push(InlineValueLocation {
5478 variable_name,
5479 scope,
5480 lookup: VariableLookupKind::Variable,
5481 row: point.row as usize,
5482 column: point.column as usize,
5483 });
5484 }
5485 }
5486 language::DebuggerTextObject::Scope => {
5487 while scopes.last().map_or_else(
5488 || false,
5489 |scope: &Range<usize>| {
5490 !(scope.contains(&capture_range.start)
5491 && scope.contains(&capture_range.end))
5492 },
5493 ) {
5494 scopes.pop();
5495 }
5496 scopes.push(capture_range);
5497 }
5498 }
5499 }
5500
5501 variables
5502}
5503
5504#[cfg(test)]
5505mod disable_ai_settings_tests {
5506 use super::*;
5507 use gpui::TestAppContext;
5508 use settings::{Settings, SettingsSources};
5509
5510 #[gpui::test]
5511 async fn test_disable_ai_settings_security(cx: &mut TestAppContext) {
5512 cx.update(|cx| {
5513 // Test 1: Default is false (AI enabled)
5514 let sources = SettingsSources {
5515 default: &Some(false),
5516 global: None,
5517 extensions: None,
5518 user: None,
5519 release_channel: None,
5520 operating_system: None,
5521 profile: None,
5522 server: None,
5523 project: &[],
5524 };
5525 let settings = DisableAiSettings::load(sources, cx).unwrap();
5526 assert_eq!(settings.disable_ai, false, "Default should allow AI");
5527
5528 // Test 2: Global true, local false -> still disabled (local cannot re-enable)
5529 let global_true = Some(true);
5530 let local_false = Some(false);
5531 let sources = SettingsSources {
5532 default: &Some(false),
5533 global: None,
5534 extensions: None,
5535 user: Some(&global_true),
5536 release_channel: None,
5537 operating_system: None,
5538 profile: None,
5539 server: None,
5540 project: &[&local_false],
5541 };
5542 let settings = DisableAiSettings::load(sources, cx).unwrap();
5543 assert_eq!(
5544 settings.disable_ai, true,
5545 "Local false cannot override global true"
5546 );
5547
5548 // Test 3: Global false, local true -> disabled (local can make more restrictive)
5549 let global_false = Some(false);
5550 let local_true = Some(true);
5551 let sources = SettingsSources {
5552 default: &Some(false),
5553 global: None,
5554 extensions: None,
5555 user: Some(&global_false),
5556 release_channel: None,
5557 operating_system: None,
5558 profile: None,
5559 server: None,
5560 project: &[&local_true],
5561 };
5562 let settings = DisableAiSettings::load(sources, cx).unwrap();
5563 assert_eq!(
5564 settings.disable_ai, true,
5565 "Local true can override global false"
5566 );
5567
5568 // Test 4: Server can only make more restrictive (set to true)
5569 let user_false = Some(false);
5570 let server_true = Some(true);
5571 let sources = SettingsSources {
5572 default: &Some(false),
5573 global: None,
5574 extensions: None,
5575 user: Some(&user_false),
5576 release_channel: None,
5577 operating_system: None,
5578 profile: None,
5579 server: Some(&server_true),
5580 project: &[],
5581 };
5582 let settings = DisableAiSettings::load(sources, cx).unwrap();
5583 assert_eq!(
5584 settings.disable_ai, true,
5585 "Server can set to true even if user is false"
5586 );
5587
5588 // Test 5: Server false cannot override user true
5589 let user_true = Some(true);
5590 let server_false = Some(false);
5591 let sources = SettingsSources {
5592 default: &Some(false),
5593 global: None,
5594 extensions: None,
5595 user: Some(&user_true),
5596 release_channel: None,
5597 operating_system: None,
5598 profile: None,
5599 server: Some(&server_false),
5600 project: &[],
5601 };
5602 let settings = DisableAiSettings::load(sources, cx).unwrap();
5603 assert_eq!(
5604 settings.disable_ai, true,
5605 "Server false cannot override user true"
5606 );
5607
5608 // Test 6: Multiple local settings, any true disables AI
5609 let global_false = Some(false);
5610 let local_false3 = Some(false);
5611 let local_true2 = Some(true);
5612 let local_false4 = Some(false);
5613 let sources = SettingsSources {
5614 default: &Some(false),
5615 global: None,
5616 extensions: None,
5617 user: Some(&global_false),
5618 release_channel: None,
5619 operating_system: None,
5620 profile: None,
5621 server: None,
5622 project: &[&local_false3, &local_true2, &local_false4],
5623 };
5624 let settings = DisableAiSettings::load(sources, cx).unwrap();
5625 assert_eq!(
5626 settings.disable_ai, true,
5627 "Any local true should disable AI"
5628 );
5629
5630 // Test 7: All three sources can independently disable AI
5631 let user_false2 = Some(false);
5632 let server_false2 = Some(false);
5633 let local_true3 = Some(true);
5634 let sources = SettingsSources {
5635 default: &Some(false),
5636 global: None,
5637 extensions: None,
5638 user: Some(&user_false2),
5639 release_channel: None,
5640 operating_system: None,
5641 profile: None,
5642 server: Some(&server_false2),
5643 project: &[&local_true3],
5644 };
5645 let settings = DisableAiSettings::load(sources, cx).unwrap();
5646 assert_eq!(
5647 settings.disable_ai, true,
5648 "Local can disable even if user and server are false"
5649 );
5650 });
5651 }
5652}