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