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