1pub mod buffer_store;
2mod color_extractor;
3pub mod connection_manager;
4pub mod debounced_delay;
5pub mod lsp_command;
6pub mod lsp_ext_command;
7pub mod lsp_store;
8pub mod prettier_store;
9pub mod project_settings;
10pub mod search;
11mod task_inventory;
12pub mod task_store;
13pub mod terminals;
14pub mod worktree_store;
15
16#[cfg(test)]
17mod project_tests;
18
19mod direnv;
20mod environment;
21pub use environment::EnvironmentErrorMessage;
22pub mod search_history;
23mod yarn;
24
25use anyhow::{anyhow, Result};
26use buffer_store::{BufferStore, BufferStoreEvent};
27use client::{
28 proto, Client, Collaborator, DevServerProjectId, PendingEntitySubscription, ProjectId,
29 TypedEnvelope, UserStore,
30};
31use clock::ReplicaId;
32use collections::{BTreeSet, HashMap, HashSet};
33use debounced_delay::DebouncedDelay;
34pub use environment::ProjectEnvironment;
35use futures::{
36 channel::mpsc::{self, UnboundedReceiver},
37 future::try_join_all,
38 StreamExt,
39};
40
41use git::{blame::Blame, repository::GitRepository};
42use gpui::{
43 AnyModel, AppContext, AsyncAppContext, BorrowAppContext, Context, EventEmitter, Hsla, Model,
44 ModelContext, SharedString, Task, WeakModel, WindowContext,
45};
46use itertools::Itertools;
47use language::{
48 language_settings::InlayHintKind, proto::split_operations, Buffer, BufferEvent,
49 CachedLspAdapter, Capability, CodeLabel, DiagnosticEntry, Documentation, File as _, Language,
50 LanguageRegistry, LanguageServerName, PointUtf16, ToOffset, ToPointUtf16, Transaction,
51 Unclipped,
52};
53use lsp::{
54 CompletionContext, CompletionItemKind, DocumentHighlightKind, LanguageServer, LanguageServerId,
55};
56use lsp_command::*;
57use node_runtime::NodeRuntime;
58use parking_lot::{Mutex, RwLock};
59pub use prettier_store::PrettierStore;
60use project_settings::{ProjectSettings, SettingsObserver, SettingsObserverEvent};
61use remote::{SshConnectionOptions, SshRemoteClient};
62use rpc::{proto::SSH_PROJECT_ID, AnyProtoClient, ErrorCode};
63use search::{SearchInputKind, SearchQuery, SearchResult};
64use search_history::SearchHistory;
65use settings::{InvalidSettingsError, Settings, SettingsLocation, SettingsStore};
66use smol::channel::Receiver;
67use snippet::Snippet;
68use snippet_provider::SnippetProvider;
69use std::{
70 borrow::Cow,
71 ops::Range,
72 path::{Component, Path, PathBuf},
73 str,
74 sync::Arc,
75 time::Duration,
76};
77use task_store::TaskStore;
78use terminals::Terminals;
79use text::{Anchor, BufferId};
80use util::{paths::compare_paths, ResultExt as _};
81use worktree::{CreatedEntry, Snapshot, Traversal};
82use worktree_store::{WorktreeStore, WorktreeStoreEvent};
83
84pub use fs::*;
85pub use language::Location;
86#[cfg(any(test, feature = "test-support"))]
87pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
88pub use task_inventory::{
89 BasicContextProvider, ContextProviderWithTasks, Inventory, TaskSourceKind,
90};
91pub use worktree::{
92 Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId, RepositoryEntry,
93 UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
94 FS_WATCH_LATENCY,
95};
96
97pub use buffer_store::ProjectTransaction;
98pub use lsp_store::{
99 DiagnosticSummary, LanguageServerLogType, LanguageServerProgress, LanguageServerPromptRequest,
100 LanguageServerStatus, LanguageServerToQuery, LspStore, LspStoreEvent,
101 SERVER_PROGRESS_THROTTLE_TIMEOUT,
102};
103
104const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
105const MAX_SEARCH_RESULT_FILES: usize = 5_000;
106const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
107
108pub trait Item {
109 fn try_open(
110 project: &Model<Project>,
111 path: &ProjectPath,
112 cx: &mut AppContext,
113 ) -> Option<Task<Result<Model<Self>>>>
114 where
115 Self: Sized;
116 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
117 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
118}
119
120#[derive(Clone)]
121pub enum OpenedBufferEvent {
122 Disconnected,
123 Ok(BufferId),
124 Err(BufferId, Arc<anyhow::Error>),
125}
126
127/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
128/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
129/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
130///
131/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
132pub struct Project {
133 active_entry: Option<ProjectEntryId>,
134 buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
135 languages: Arc<LanguageRegistry>,
136 client: Arc<client::Client>,
137 join_project_response_message_id: u32,
138 task_store: Model<TaskStore>,
139 user_store: Model<UserStore>,
140 fs: Arc<dyn Fs>,
141 ssh_client: Option<Model<SshRemoteClient>>,
142 client_state: ProjectClientState,
143 collaborators: HashMap<proto::PeerId, Collaborator>,
144 client_subscriptions: Vec<client::Subscription>,
145 worktree_store: Model<WorktreeStore>,
146 buffer_store: Model<BufferStore>,
147 lsp_store: Model<LspStore>,
148 _subscriptions: Vec<gpui::Subscription>,
149 buffers_needing_diff: HashSet<WeakModel<Buffer>>,
150 git_diff_debouncer: DebouncedDelay<Self>,
151 remotely_created_models: Arc<Mutex<RemotelyCreatedModels>>,
152 terminals: Terminals,
153 node: Option<NodeRuntime>,
154 hosted_project_id: Option<ProjectId>,
155 dev_server_project_id: Option<client::DevServerProjectId>,
156 search_history: SearchHistory,
157 search_included_history: SearchHistory,
158 search_excluded_history: SearchHistory,
159 snippets: Model<SnippetProvider>,
160 environment: Model<ProjectEnvironment>,
161 settings_observer: Model<SettingsObserver>,
162}
163
164#[derive(Default)]
165struct RemotelyCreatedModels {
166 worktrees: Vec<Model<Worktree>>,
167 buffers: Vec<Model<Buffer>>,
168 retain_count: usize,
169}
170
171struct RemotelyCreatedModelGuard {
172 remote_models: std::sync::Weak<Mutex<RemotelyCreatedModels>>,
173}
174
175impl Drop for RemotelyCreatedModelGuard {
176 fn drop(&mut self) {
177 if let Some(remote_models) = self.remote_models.upgrade() {
178 let mut remote_models = remote_models.lock();
179 assert!(
180 remote_models.retain_count > 0,
181 "RemotelyCreatedModelGuard dropped too many times"
182 );
183 remote_models.retain_count -= 1;
184 if remote_models.retain_count == 0 {
185 remote_models.buffers.clear();
186 remote_models.worktrees.clear();
187 }
188 }
189 }
190}
191/// Message ordered with respect to buffer operations
192#[derive(Debug)]
193enum BufferOrderedMessage {
194 Operation {
195 buffer_id: BufferId,
196 operation: proto::Operation,
197 },
198 LanguageServerUpdate {
199 language_server_id: LanguageServerId,
200 message: proto::update_language_server::Variant,
201 },
202 Resync,
203}
204
205#[derive(Debug)]
206enum ProjectClientState {
207 Local,
208 Shared {
209 remote_id: u64,
210 },
211 Remote {
212 sharing_has_stopped: bool,
213 capability: Capability,
214 remote_id: u64,
215 replica_id: ReplicaId,
216 in_room: bool,
217 },
218}
219
220#[derive(Clone, Debug, PartialEq)]
221pub enum Event {
222 LanguageServerAdded(LanguageServerId),
223 LanguageServerRemoved(LanguageServerId),
224 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
225 Notification(String),
226 LocalSettingsUpdated(Result<(), InvalidSettingsError>),
227 LanguageServerPrompt(LanguageServerPromptRequest),
228 LanguageNotFound(Model<Buffer>),
229 ActiveEntryChanged(Option<ProjectEntryId>),
230 ActivateProjectPanel,
231 WorktreeAdded,
232 WorktreeOrderChanged,
233 WorktreeRemoved(WorktreeId),
234 WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
235 WorktreeUpdatedGitRepositories,
236 DiskBasedDiagnosticsStarted {
237 language_server_id: LanguageServerId,
238 },
239 DiskBasedDiagnosticsFinished {
240 language_server_id: LanguageServerId,
241 },
242 DiagnosticsUpdated {
243 path: ProjectPath,
244 language_server_id: LanguageServerId,
245 },
246 RemoteIdChanged(Option<u64>),
247 DisconnectedFromHost,
248 DisconnectedFromSshRemote,
249 Closed,
250 DeletedEntry(ProjectEntryId),
251 CollaboratorUpdated {
252 old_peer_id: proto::PeerId,
253 new_peer_id: proto::PeerId,
254 },
255 CollaboratorJoined(proto::PeerId),
256 CollaboratorLeft(proto::PeerId),
257 HostReshared,
258 Reshared,
259 Rejoined,
260 RefreshInlayHints,
261 RevealInProjectPanel(ProjectEntryId),
262 SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
263}
264
265#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
266pub struct ProjectPath {
267 pub worktree_id: WorktreeId,
268 pub path: Arc<Path>,
269}
270
271impl ProjectPath {
272 pub fn from_proto(p: proto::ProjectPath) -> Self {
273 Self {
274 worktree_id: WorktreeId::from_proto(p.worktree_id),
275 path: Arc::from(PathBuf::from(p.path)),
276 }
277 }
278
279 pub fn to_proto(&self) -> proto::ProjectPath {
280 proto::ProjectPath {
281 worktree_id: self.worktree_id.to_proto(),
282 path: self.path.to_string_lossy().to_string(),
283 }
284 }
285}
286
287#[derive(Debug, Clone, PartialEq, Eq)]
288pub struct InlayHint {
289 pub position: language::Anchor,
290 pub label: InlayHintLabel,
291 pub kind: Option<InlayHintKind>,
292 pub padding_left: bool,
293 pub padding_right: bool,
294 pub tooltip: Option<InlayHintTooltip>,
295 pub resolve_state: ResolveState,
296}
297
298/// The user's intent behind a given completion confirmation
299#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
300pub enum CompletionIntent {
301 /// The user intends to 'commit' this result, if possible
302 /// completion confirmations should run side effects
303 Complete,
304 /// The user intends to continue 'composing' this completion
305 /// completion confirmations should not run side effects and
306 /// let the user continue composing their action
307 Compose,
308}
309
310impl CompletionIntent {
311 pub fn is_complete(&self) -> bool {
312 self == &Self::Complete
313 }
314
315 pub fn is_compose(&self) -> bool {
316 self == &Self::Compose
317 }
318}
319
320/// A completion provided by a language server
321#[derive(Clone)]
322pub struct Completion {
323 /// The range of the buffer that will be replaced.
324 pub old_range: Range<Anchor>,
325 /// The new text that will be inserted.
326 pub new_text: String,
327 /// A label for this completion that is shown in the menu.
328 pub label: CodeLabel,
329 /// The id of the language server that produced this completion.
330 pub server_id: LanguageServerId,
331 /// The documentation for this completion.
332 pub documentation: Option<Documentation>,
333 /// The raw completion provided by the language server.
334 pub lsp_completion: lsp::CompletionItem,
335 /// An optional callback to invoke when this completion is confirmed.
336 /// Returns, whether new completions should be retriggered after the current one.
337 /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
338 /// if no confirmation is provided or `false` is returned, the completion will be committed.
339 pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut WindowContext) -> bool>>,
340}
341
342impl std::fmt::Debug for Completion {
343 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344 f.debug_struct("Completion")
345 .field("old_range", &self.old_range)
346 .field("new_text", &self.new_text)
347 .field("label", &self.label)
348 .field("server_id", &self.server_id)
349 .field("documentation", &self.documentation)
350 .field("lsp_completion", &self.lsp_completion)
351 .finish()
352 }
353}
354
355/// A completion provided by a language server
356#[derive(Clone, Debug)]
357pub(crate) struct CoreCompletion {
358 old_range: Range<Anchor>,
359 new_text: String,
360 server_id: LanguageServerId,
361 lsp_completion: lsp::CompletionItem,
362}
363
364/// A code action provided by a language server.
365#[derive(Clone, Debug)]
366pub struct CodeAction {
367 /// The id of the language server that produced this code action.
368 pub server_id: LanguageServerId,
369 /// The range of the buffer where this code action is applicable.
370 pub range: Range<Anchor>,
371 /// The raw code action provided by the language server.
372 pub lsp_action: lsp::CodeAction,
373}
374
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub enum ResolveState {
377 Resolved,
378 CanResolve(LanguageServerId, Option<lsp::LSPAny>),
379 Resolving,
380}
381
382impl InlayHint {
383 pub fn text(&self) -> String {
384 match &self.label {
385 InlayHintLabel::String(s) => s.to_owned(),
386 InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
387 }
388 }
389}
390
391#[derive(Debug, Clone, PartialEq, Eq)]
392pub enum InlayHintLabel {
393 String(String),
394 LabelParts(Vec<InlayHintLabelPart>),
395}
396
397#[derive(Debug, Clone, PartialEq, Eq)]
398pub struct InlayHintLabelPart {
399 pub value: String,
400 pub tooltip: Option<InlayHintLabelPartTooltip>,
401 pub location: Option<(LanguageServerId, lsp::Location)>,
402}
403
404#[derive(Debug, Clone, PartialEq, Eq)]
405pub enum InlayHintTooltip {
406 String(String),
407 MarkupContent(MarkupContent),
408}
409
410#[derive(Debug, Clone, PartialEq, Eq)]
411pub enum InlayHintLabelPartTooltip {
412 String(String),
413 MarkupContent(MarkupContent),
414}
415
416#[derive(Debug, Clone, PartialEq, Eq)]
417pub struct MarkupContent {
418 pub kind: HoverBlockKind,
419 pub value: String,
420}
421
422#[derive(Debug, Clone)]
423pub struct LocationLink {
424 pub origin: Option<Location>,
425 pub target: Location,
426}
427
428#[derive(Debug)]
429pub struct DocumentHighlight {
430 pub range: Range<language::Anchor>,
431 pub kind: DocumentHighlightKind,
432}
433
434#[derive(Clone, Debug)]
435pub struct Symbol {
436 pub language_server_name: LanguageServerName,
437 pub source_worktree_id: WorktreeId,
438 pub path: ProjectPath,
439 pub label: CodeLabel,
440 pub name: String,
441 pub kind: lsp::SymbolKind,
442 pub range: Range<Unclipped<PointUtf16>>,
443 pub signature: [u8; 32],
444}
445
446#[derive(Clone, Debug, PartialEq)]
447pub struct HoverBlock {
448 pub text: String,
449 pub kind: HoverBlockKind,
450}
451
452#[derive(Clone, Debug, PartialEq, Eq)]
453pub enum HoverBlockKind {
454 PlainText,
455 Markdown,
456 Code { language: String },
457}
458
459#[derive(Debug, Clone)]
460pub struct Hover {
461 pub contents: Vec<HoverBlock>,
462 pub range: Option<Range<language::Anchor>>,
463 pub language: Option<Arc<Language>>,
464}
465
466impl Hover {
467 pub fn is_empty(&self) -> bool {
468 self.contents.iter().all(|block| block.text.is_empty())
469 }
470}
471
472enum EntitySubscription {
473 Project(PendingEntitySubscription<Project>),
474 BufferStore(PendingEntitySubscription<BufferStore>),
475 WorktreeStore(PendingEntitySubscription<WorktreeStore>),
476 LspStore(PendingEntitySubscription<LspStore>),
477 SettingsObserver(PendingEntitySubscription<SettingsObserver>),
478}
479
480#[derive(Clone)]
481pub enum DirectoryLister {
482 Project(Model<Project>),
483 Local(Arc<dyn Fs>),
484}
485
486impl DirectoryLister {
487 pub fn is_local(&self, cx: &AppContext) -> bool {
488 match self {
489 DirectoryLister::Local(_) => true,
490 DirectoryLister::Project(project) => project.read(cx).is_local(),
491 }
492 }
493
494 pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &AppContext) -> Cow<'a, str> {
495 if self.is_local(cx) {
496 shellexpand::tilde(path)
497 } else {
498 Cow::from(path)
499 }
500 }
501
502 pub fn default_query(&self, cx: &mut AppContext) -> String {
503 if let DirectoryLister::Project(project) = self {
504 if let Some(worktree) = project.read(cx).visible_worktrees(cx).next() {
505 return worktree.read(cx).abs_path().to_string_lossy().to_string();
506 }
507 };
508 "~/".to_string()
509 }
510
511 pub fn list_directory(&self, path: String, cx: &mut AppContext) -> Task<Result<Vec<PathBuf>>> {
512 match self {
513 DirectoryLister::Project(project) => {
514 project.update(cx, |project, cx| project.list_directory(path, cx))
515 }
516 DirectoryLister::Local(fs) => {
517 let fs = fs.clone();
518 cx.background_executor().spawn(async move {
519 let mut results = vec![];
520 let expanded = shellexpand::tilde(&path);
521 let query = Path::new(expanded.as_ref());
522 let mut response = fs.read_dir(query).await?;
523 while let Some(path) = response.next().await {
524 if let Some(file_name) = path?.file_name() {
525 results.push(PathBuf::from(file_name.to_os_string()));
526 }
527 }
528 Ok(results)
529 })
530 }
531 }
532 }
533}
534
535#[cfg(any(test, feature = "test-support"))]
536pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
537 trigger_kind: lsp::CompletionTriggerKind::INVOKED,
538 trigger_character: None,
539};
540
541impl Project {
542 pub fn init_settings(cx: &mut AppContext) {
543 WorktreeSettings::register(cx);
544 ProjectSettings::register(cx);
545 }
546
547 pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
548 connection_manager::init(client.clone(), cx);
549 Self::init_settings(cx);
550
551 let client: AnyProtoClient = client.clone().into();
552 client.add_model_message_handler(Self::handle_add_collaborator);
553 client.add_model_message_handler(Self::handle_update_project_collaborator);
554 client.add_model_message_handler(Self::handle_remove_collaborator);
555 client.add_model_message_handler(Self::handle_update_project);
556 client.add_model_message_handler(Self::handle_unshare_project);
557 client.add_model_request_handler(Self::handle_update_buffer);
558 client.add_model_message_handler(Self::handle_update_worktree);
559 client.add_model_request_handler(Self::handle_synchronize_buffers);
560
561 client.add_model_request_handler(Self::handle_search_candidate_buffers);
562 client.add_model_request_handler(Self::handle_open_buffer_by_id);
563 client.add_model_request_handler(Self::handle_open_buffer_by_path);
564 client.add_model_request_handler(Self::handle_open_new_buffer);
565 client.add_model_message_handler(Self::handle_create_buffer_for_peer);
566
567 WorktreeStore::init(&client);
568 BufferStore::init(&client);
569 LspStore::init(&client);
570 SettingsObserver::init(&client);
571 TaskStore::init(Some(&client));
572 }
573
574 pub fn local(
575 client: Arc<Client>,
576 node: NodeRuntime,
577 user_store: Model<UserStore>,
578 languages: Arc<LanguageRegistry>,
579 fs: Arc<dyn Fs>,
580 env: Option<HashMap<String, String>>,
581 cx: &mut AppContext,
582 ) -> Model<Self> {
583 cx.new_model(|cx: &mut ModelContext<Self>| {
584 let (tx, rx) = mpsc::unbounded();
585 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
586 .detach();
587 let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
588 let worktree_store = cx.new_model(|_| WorktreeStore::local(false, fs.clone()));
589 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
590 .detach();
591
592 let buffer_store = cx.new_model(|cx| BufferStore::local(worktree_store.clone(), cx));
593 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
594 .detach();
595
596 let prettier_store = cx.new_model(|cx| {
597 PrettierStore::new(
598 node.clone(),
599 fs.clone(),
600 languages.clone(),
601 worktree_store.clone(),
602 cx,
603 )
604 });
605
606 let environment = ProjectEnvironment::new(&worktree_store, env, cx);
607
608 let task_store = cx.new_model(|cx| {
609 TaskStore::local(
610 fs.clone(),
611 buffer_store.downgrade(),
612 worktree_store.clone(),
613 environment.clone(),
614 cx,
615 )
616 });
617
618 let settings_observer = cx.new_model(|cx| {
619 SettingsObserver::new_local(
620 fs.clone(),
621 worktree_store.clone(),
622 task_store.clone(),
623 cx,
624 )
625 });
626 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
627 .detach();
628
629 let lsp_store = cx.new_model(|cx| {
630 LspStore::new_local(
631 buffer_store.clone(),
632 worktree_store.clone(),
633 prettier_store.clone(),
634 environment.clone(),
635 languages.clone(),
636 Some(client.http_client()),
637 fs.clone(),
638 cx,
639 )
640 });
641 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
642
643 Self {
644 buffer_ordered_messages_tx: tx,
645 collaborators: Default::default(),
646 worktree_store,
647 buffer_store,
648 lsp_store,
649 join_project_response_message_id: 0,
650 client_state: ProjectClientState::Local,
651 client_subscriptions: Vec::new(),
652 _subscriptions: vec![cx.on_release(Self::release)],
653 active_entry: None,
654 snippets,
655 languages,
656 client,
657 task_store,
658 user_store,
659 settings_observer,
660 fs,
661 ssh_client: None,
662 buffers_needing_diff: Default::default(),
663 git_diff_debouncer: DebouncedDelay::new(),
664 terminals: Terminals {
665 local_handles: Vec::new(),
666 },
667 node: Some(node),
668 hosted_project_id: None,
669 dev_server_project_id: None,
670 search_history: Self::new_search_history(),
671 environment,
672 remotely_created_models: Default::default(),
673
674 search_included_history: Self::new_search_history(),
675 search_excluded_history: Self::new_search_history(),
676 }
677 })
678 }
679
680 pub fn ssh(
681 ssh: Model<SshRemoteClient>,
682 client: Arc<Client>,
683 node: NodeRuntime,
684 user_store: Model<UserStore>,
685 languages: Arc<LanguageRegistry>,
686 fs: Arc<dyn Fs>,
687 cx: &mut AppContext,
688 ) -> Model<Self> {
689 cx.new_model(|cx: &mut ModelContext<Self>| {
690 let (tx, rx) = mpsc::unbounded();
691 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
692 .detach();
693 let global_snippets_dir = paths::config_dir().join("snippets");
694 let snippets =
695 SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
696
697 let ssh_proto = ssh.read(cx).to_proto_client();
698 let worktree_store =
699 cx.new_model(|_| WorktreeStore::remote(false, ssh_proto.clone(), 0, None));
700 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
701 .detach();
702
703 let buffer_store = cx.new_model(|cx| {
704 BufferStore::remote(
705 worktree_store.clone(),
706 ssh.read(cx).to_proto_client(),
707 SSH_PROJECT_ID,
708 cx,
709 )
710 });
711 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
712 .detach();
713
714 let task_store = cx.new_model(|cx| {
715 TaskStore::remote(
716 fs.clone(),
717 buffer_store.downgrade(),
718 worktree_store.clone(),
719 ssh.read(cx).to_proto_client(),
720 SSH_PROJECT_ID,
721 cx,
722 )
723 });
724
725 let settings_observer = cx.new_model(|cx| {
726 SettingsObserver::new_ssh(
727 ssh_proto.clone(),
728 worktree_store.clone(),
729 task_store.clone(),
730 cx,
731 )
732 });
733 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
734 .detach();
735
736 let environment = ProjectEnvironment::new(&worktree_store, None, cx);
737 let lsp_store = cx.new_model(|cx| {
738 LspStore::new_remote(
739 buffer_store.clone(),
740 worktree_store.clone(),
741 languages.clone(),
742 ssh_proto.clone(),
743 SSH_PROJECT_ID,
744 cx,
745 )
746 });
747 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
748
749 cx.on_release(|this, cx| {
750 if let Some(ssh_client) = this.ssh_client.as_ref() {
751 ssh_client
752 .read(cx)
753 .to_proto_client()
754 .send(proto::ShutdownRemoteServer {})
755 .log_err();
756 }
757 })
758 .detach();
759
760 cx.subscribe(&ssh, Self::on_ssh_event).detach();
761 cx.observe(&ssh, |_, _, cx| cx.notify()).detach();
762
763 let this = Self {
764 buffer_ordered_messages_tx: tx,
765 collaborators: Default::default(),
766 worktree_store,
767 buffer_store,
768 lsp_store,
769 join_project_response_message_id: 0,
770 client_state: ProjectClientState::Local,
771 client_subscriptions: Vec::new(),
772 _subscriptions: vec![cx.on_release(Self::release)],
773 active_entry: None,
774 snippets,
775 languages,
776 client,
777 task_store,
778 user_store,
779 settings_observer,
780 fs,
781 ssh_client: Some(ssh.clone()),
782 buffers_needing_diff: Default::default(),
783 git_diff_debouncer: DebouncedDelay::new(),
784 terminals: Terminals {
785 local_handles: Vec::new(),
786 },
787 node: Some(node),
788 hosted_project_id: None,
789 dev_server_project_id: None,
790 search_history: Self::new_search_history(),
791 environment,
792 remotely_created_models: Default::default(),
793
794 search_included_history: Self::new_search_history(),
795 search_excluded_history: Self::new_search_history(),
796 };
797
798 let ssh = ssh.read(cx);
799 ssh.subscribe_to_entity(SSH_PROJECT_ID, &cx.handle());
800 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.buffer_store);
801 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.worktree_store);
802 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.lsp_store);
803 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.settings_observer);
804
805 ssh_proto.add_model_message_handler(Self::handle_create_buffer_for_peer);
806 ssh_proto.add_model_message_handler(Self::handle_update_worktree);
807 ssh_proto.add_model_message_handler(Self::handle_update_project);
808 ssh_proto.add_model_request_handler(BufferStore::handle_update_buffer);
809 BufferStore::init(&ssh_proto);
810 LspStore::init(&ssh_proto);
811 SettingsObserver::init(&ssh_proto);
812 TaskStore::init(Some(&ssh_proto));
813
814 this
815 })
816 }
817
818 pub async fn remote(
819 remote_id: u64,
820 client: Arc<Client>,
821 user_store: Model<UserStore>,
822 languages: Arc<LanguageRegistry>,
823 fs: Arc<dyn Fs>,
824 cx: AsyncAppContext,
825 ) -> Result<Model<Self>> {
826 let project =
827 Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
828 cx.update(|cx| {
829 connection_manager::Manager::global(cx).update(cx, |manager, cx| {
830 manager.maintain_project_connection(&project, cx)
831 })
832 })?;
833 Ok(project)
834 }
835
836 pub async fn in_room(
837 remote_id: u64,
838 client: Arc<Client>,
839 user_store: Model<UserStore>,
840 languages: Arc<LanguageRegistry>,
841 fs: Arc<dyn Fs>,
842 cx: AsyncAppContext,
843 ) -> Result<Model<Self>> {
844 client.authenticate_and_connect(true, &cx).await?;
845
846 let subscriptions = [
847 EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
848 EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
849 EntitySubscription::WorktreeStore(
850 client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
851 ),
852 EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
853 EntitySubscription::SettingsObserver(
854 client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
855 ),
856 ];
857 let response = client
858 .request_envelope(proto::JoinProject {
859 project_id: remote_id,
860 })
861 .await?;
862 Self::from_join_project_response(
863 response,
864 subscriptions,
865 client,
866 false,
867 user_store,
868 languages,
869 fs,
870 cx,
871 )
872 .await
873 }
874
875 #[allow(clippy::too_many_arguments)]
876 async fn from_join_project_response(
877 response: TypedEnvelope<proto::JoinProjectResponse>,
878 subscriptions: [EntitySubscription; 5],
879 client: Arc<Client>,
880 run_tasks: bool,
881 user_store: Model<UserStore>,
882 languages: Arc<LanguageRegistry>,
883 fs: Arc<dyn Fs>,
884 mut cx: AsyncAppContext,
885 ) -> Result<Model<Self>> {
886 let remote_id = response.payload.project_id;
887 let role = response.payload.role();
888
889 let worktree_store = cx.new_model(|_| {
890 WorktreeStore::remote(
891 true,
892 client.clone().into(),
893 response.payload.project_id,
894 response
895 .payload
896 .dev_server_project_id
897 .map(DevServerProjectId),
898 )
899 })?;
900 let buffer_store = cx.new_model(|cx| {
901 BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
902 })?;
903
904 let lsp_store = cx.new_model(|cx| {
905 let mut lsp_store = LspStore::new_remote(
906 buffer_store.clone(),
907 worktree_store.clone(),
908 languages.clone(),
909 client.clone().into(),
910 remote_id,
911 cx,
912 );
913 lsp_store.set_language_server_statuses_from_proto(response.payload.language_servers);
914 lsp_store
915 })?;
916
917 let task_store = cx.new_model(|cx| {
918 if run_tasks {
919 TaskStore::remote(
920 fs.clone(),
921 buffer_store.downgrade(),
922 worktree_store.clone(),
923 client.clone().into(),
924 remote_id,
925 cx,
926 )
927 } else {
928 TaskStore::Noop
929 }
930 })?;
931
932 let settings_observer = cx.new_model(|cx| {
933 SettingsObserver::new_remote(worktree_store.clone(), task_store.clone(), cx)
934 })?;
935
936 let this = cx.new_model(|cx| {
937 let replica_id = response.payload.replica_id as ReplicaId;
938
939 let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
940
941 let mut worktrees = Vec::new();
942 for worktree in response.payload.worktrees {
943 let worktree =
944 Worktree::remote(remote_id, replica_id, worktree, client.clone().into(), cx);
945 worktrees.push(worktree);
946 }
947
948 let (tx, rx) = mpsc::unbounded();
949 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
950 .detach();
951
952 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
953 .detach();
954
955 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
956 .detach();
957 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
958 cx.subscribe(&settings_observer, Self::on_settings_observer_event)
959 .detach();
960
961 let mut this = Self {
962 buffer_ordered_messages_tx: tx,
963 buffer_store: buffer_store.clone(),
964 worktree_store: worktree_store.clone(),
965 lsp_store: lsp_store.clone(),
966 active_entry: None,
967 collaborators: Default::default(),
968 join_project_response_message_id: response.message_id,
969 languages,
970 user_store: user_store.clone(),
971 task_store,
972 snippets,
973 fs,
974 ssh_client: None,
975 settings_observer: settings_observer.clone(),
976 client_subscriptions: Default::default(),
977 _subscriptions: vec![cx.on_release(Self::release)],
978 client: client.clone(),
979 client_state: ProjectClientState::Remote {
980 sharing_has_stopped: false,
981 capability: Capability::ReadWrite,
982 remote_id,
983 replica_id,
984 in_room: response.payload.dev_server_project_id.is_none(),
985 },
986 buffers_needing_diff: Default::default(),
987 git_diff_debouncer: DebouncedDelay::new(),
988 terminals: Terminals {
989 local_handles: Vec::new(),
990 },
991 node: None,
992 hosted_project_id: None,
993 dev_server_project_id: response
994 .payload
995 .dev_server_project_id
996 .map(DevServerProjectId),
997 search_history: Self::new_search_history(),
998 search_included_history: Self::new_search_history(),
999 search_excluded_history: Self::new_search_history(),
1000 environment: ProjectEnvironment::new(&worktree_store, None, cx),
1001 remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1002 };
1003 this.set_role(role, cx);
1004 for worktree in worktrees {
1005 this.add_worktree(&worktree, cx);
1006 }
1007 this
1008 })?;
1009
1010 let subscriptions = subscriptions
1011 .into_iter()
1012 .map(|s| match s {
1013 EntitySubscription::BufferStore(subscription) => {
1014 subscription.set_model(&buffer_store, &mut cx)
1015 }
1016 EntitySubscription::WorktreeStore(subscription) => {
1017 subscription.set_model(&worktree_store, &mut cx)
1018 }
1019 EntitySubscription::SettingsObserver(subscription) => {
1020 subscription.set_model(&settings_observer, &mut cx)
1021 }
1022 EntitySubscription::Project(subscription) => subscription.set_model(&this, &mut cx),
1023 EntitySubscription::LspStore(subscription) => {
1024 subscription.set_model(&lsp_store, &mut cx)
1025 }
1026 })
1027 .collect::<Vec<_>>();
1028
1029 let user_ids = response
1030 .payload
1031 .collaborators
1032 .iter()
1033 .map(|peer| peer.user_id)
1034 .collect();
1035 user_store
1036 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
1037 .await?;
1038
1039 this.update(&mut cx, |this, cx| {
1040 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1041 this.client_subscriptions.extend(subscriptions);
1042 anyhow::Ok(())
1043 })??;
1044
1045 Ok(this)
1046 }
1047
1048 pub async fn hosted(
1049 remote_id: ProjectId,
1050 user_store: Model<UserStore>,
1051 client: Arc<Client>,
1052 languages: Arc<LanguageRegistry>,
1053 fs: Arc<dyn Fs>,
1054 cx: AsyncAppContext,
1055 ) -> Result<Model<Self>> {
1056 client.authenticate_and_connect(true, &cx).await?;
1057
1058 let subscriptions = [
1059 EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id.0)?),
1060 EntitySubscription::BufferStore(
1061 client.subscribe_to_entity::<BufferStore>(remote_id.0)?,
1062 ),
1063 EntitySubscription::WorktreeStore(
1064 client.subscribe_to_entity::<WorktreeStore>(remote_id.0)?,
1065 ),
1066 EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id.0)?),
1067 EntitySubscription::SettingsObserver(
1068 client.subscribe_to_entity::<SettingsObserver>(remote_id.0)?,
1069 ),
1070 ];
1071 let response = client
1072 .request_envelope(proto::JoinHostedProject {
1073 project_id: remote_id.0,
1074 })
1075 .await?;
1076 Self::from_join_project_response(
1077 response,
1078 subscriptions,
1079 client,
1080 true,
1081 user_store,
1082 languages,
1083 fs,
1084 cx,
1085 )
1086 .await
1087 }
1088
1089 fn new_search_history() -> SearchHistory {
1090 SearchHistory::new(
1091 Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1092 search_history::QueryInsertionBehavior::AlwaysInsert,
1093 )
1094 }
1095
1096 fn release(&mut self, cx: &mut AppContext) {
1097 match &self.client_state {
1098 ProjectClientState::Local => {}
1099 ProjectClientState::Shared { .. } => {
1100 let _ = self.unshare_internal(cx);
1101 }
1102 ProjectClientState::Remote { remote_id, .. } => {
1103 let _ = self.client.send(proto::LeaveProject {
1104 project_id: *remote_id,
1105 });
1106 self.disconnected_from_host_internal(cx);
1107 }
1108 }
1109 }
1110
1111 #[cfg(any(test, feature = "test-support"))]
1112 pub async fn example(
1113 root_paths: impl IntoIterator<Item = &Path>,
1114 cx: &mut AsyncAppContext,
1115 ) -> Model<Project> {
1116 use clock::FakeSystemClock;
1117
1118 let fs = Arc::new(RealFs::default());
1119 let languages = LanguageRegistry::test(cx.background_executor().clone());
1120 let clock = Arc::new(FakeSystemClock::default());
1121 let http_client = http_client::FakeHttpClient::with_404_response();
1122 let client = cx
1123 .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1124 .unwrap();
1125 let user_store = cx
1126 .new_model(|cx| UserStore::new(client.clone(), cx))
1127 .unwrap();
1128 let project = cx
1129 .update(|cx| {
1130 Project::local(
1131 client,
1132 node_runtime::NodeRuntime::unavailable(),
1133 user_store,
1134 Arc::new(languages),
1135 fs,
1136 None,
1137 cx,
1138 )
1139 })
1140 .unwrap();
1141 for path in root_paths {
1142 let (tree, _) = project
1143 .update(cx, |project, cx| {
1144 project.find_or_create_worktree(path, true, cx)
1145 })
1146 .unwrap()
1147 .await
1148 .unwrap();
1149 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1150 .unwrap()
1151 .await;
1152 }
1153 project
1154 }
1155
1156 #[cfg(any(test, feature = "test-support"))]
1157 pub async fn test(
1158 fs: Arc<dyn Fs>,
1159 root_paths: impl IntoIterator<Item = &Path>,
1160 cx: &mut gpui::TestAppContext,
1161 ) -> Model<Project> {
1162 use clock::FakeSystemClock;
1163
1164 let languages = LanguageRegistry::test(cx.executor());
1165 let clock = Arc::new(FakeSystemClock::default());
1166 let http_client = http_client::FakeHttpClient::with_404_response();
1167 let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1168 let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
1169 let project = cx.update(|cx| {
1170 Project::local(
1171 client,
1172 node_runtime::NodeRuntime::unavailable(),
1173 user_store,
1174 Arc::new(languages),
1175 fs,
1176 None,
1177 cx,
1178 )
1179 });
1180 for path in root_paths {
1181 let (tree, _) = project
1182 .update(cx, |project, cx| {
1183 project.find_or_create_worktree(path, true, cx)
1184 })
1185 .await
1186 .unwrap();
1187
1188 project.update(cx, |project, cx| {
1189 let tree_id = tree.read(cx).id();
1190 project.environment.update(cx, |environment, _| {
1191 environment.set_cached(&[(tree_id, HashMap::default())])
1192 });
1193 });
1194
1195 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1196 .await;
1197 }
1198 project
1199 }
1200
1201 pub fn lsp_store(&self) -> Model<LspStore> {
1202 self.lsp_store.clone()
1203 }
1204
1205 pub fn worktree_store(&self) -> Model<WorktreeStore> {
1206 self.worktree_store.clone()
1207 }
1208
1209 pub fn buffer_for_id(&self, remote_id: BufferId, cx: &AppContext) -> Option<Model<Buffer>> {
1210 self.buffer_store.read(cx).get(remote_id)
1211 }
1212
1213 pub fn languages(&self) -> &Arc<LanguageRegistry> {
1214 &self.languages
1215 }
1216
1217 pub fn client(&self) -> Arc<Client> {
1218 self.client.clone()
1219 }
1220
1221 pub fn user_store(&self) -> Model<UserStore> {
1222 self.user_store.clone()
1223 }
1224
1225 pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1226 self.node.as_ref()
1227 }
1228
1229 pub fn opened_buffers(&self, cx: &AppContext) -> Vec<Model<Buffer>> {
1230 self.buffer_store.read(cx).buffers().collect()
1231 }
1232
1233 pub fn cli_environment(&self, cx: &AppContext) -> Option<HashMap<String, String>> {
1234 self.environment.read(cx).get_cli_environment()
1235 }
1236
1237 pub fn shell_environment_errors<'a>(
1238 &'a self,
1239 cx: &'a AppContext,
1240 ) -> impl Iterator<Item = (&'a WorktreeId, &'a EnvironmentErrorMessage)> {
1241 self.environment.read(cx).environment_errors()
1242 }
1243
1244 pub fn remove_environment_error(
1245 &mut self,
1246 cx: &mut ModelContext<Self>,
1247 worktree_id: WorktreeId,
1248 ) {
1249 self.environment.update(cx, |environment, _| {
1250 environment.remove_environment_error(worktree_id);
1251 });
1252 }
1253
1254 #[cfg(any(test, feature = "test-support"))]
1255 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
1256 self.buffer_store
1257 .read(cx)
1258 .get_by_path(&path.into(), cx)
1259 .is_some()
1260 }
1261
1262 pub fn fs(&self) -> &Arc<dyn Fs> {
1263 &self.fs
1264 }
1265
1266 pub fn remote_id(&self) -> Option<u64> {
1267 match self.client_state {
1268 ProjectClientState::Local => None,
1269 ProjectClientState::Shared { remote_id, .. }
1270 | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1271 }
1272 }
1273
1274 pub fn hosted_project_id(&self) -> Option<ProjectId> {
1275 self.hosted_project_id
1276 }
1277
1278 pub fn dev_server_project_id(&self) -> Option<DevServerProjectId> {
1279 self.dev_server_project_id
1280 }
1281
1282 pub fn supports_terminal(&self, cx: &AppContext) -> bool {
1283 if self.is_local() {
1284 return true;
1285 }
1286 if self.is_via_ssh() {
1287 return true;
1288 }
1289 let Some(id) = self.dev_server_project_id else {
1290 return false;
1291 };
1292 let Some(server) = dev_server_projects::Store::global(cx)
1293 .read(cx)
1294 .dev_server_for_project(id)
1295 else {
1296 return false;
1297 };
1298 server.ssh_connection_string.is_some()
1299 }
1300
1301 pub fn ssh_connection_string(&self, cx: &AppContext) -> Option<SharedString> {
1302 if let Some(ssh_state) = &self.ssh_client {
1303 return Some(ssh_state.read(cx).connection_string().into());
1304 }
1305 let dev_server_id = self.dev_server_project_id()?;
1306 dev_server_projects::Store::global(cx)
1307 .read(cx)
1308 .dev_server_for_project(dev_server_id)?
1309 .ssh_connection_string
1310 .clone()
1311 }
1312
1313 pub fn ssh_connection_state(&self, cx: &AppContext) -> Option<remote::ConnectionState> {
1314 self.ssh_client
1315 .as_ref()
1316 .map(|ssh| ssh.read(cx).connection_state())
1317 }
1318
1319 pub fn ssh_connection_options(&self, cx: &AppContext) -> Option<SshConnectionOptions> {
1320 self.ssh_client
1321 .as_ref()
1322 .map(|ssh| ssh.read(cx).connection_options())
1323 }
1324
1325 pub fn replica_id(&self) -> ReplicaId {
1326 match self.client_state {
1327 ProjectClientState::Remote { replica_id, .. } => replica_id,
1328 _ => {
1329 if self.ssh_client.is_some() {
1330 1
1331 } else {
1332 0
1333 }
1334 }
1335 }
1336 }
1337
1338 pub fn task_store(&self) -> &Model<TaskStore> {
1339 &self.task_store
1340 }
1341
1342 pub fn snippets(&self) -> &Model<SnippetProvider> {
1343 &self.snippets
1344 }
1345
1346 pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1347 match kind {
1348 SearchInputKind::Query => &self.search_history,
1349 SearchInputKind::Include => &self.search_included_history,
1350 SearchInputKind::Exclude => &self.search_excluded_history,
1351 }
1352 }
1353
1354 pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1355 match kind {
1356 SearchInputKind::Query => &mut self.search_history,
1357 SearchInputKind::Include => &mut self.search_included_history,
1358 SearchInputKind::Exclude => &mut self.search_excluded_history,
1359 }
1360 }
1361
1362 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1363 &self.collaborators
1364 }
1365
1366 pub fn host(&self) -> Option<&Collaborator> {
1367 self.collaborators.values().find(|c| c.replica_id == 0)
1368 }
1369
1370 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut AppContext) {
1371 self.worktree_store.update(cx, |store, _| {
1372 store.set_worktrees_reordered(worktrees_reordered);
1373 });
1374 }
1375
1376 /// Collect all worktrees, including ones that don't appear in the project panel
1377 pub fn worktrees<'a>(
1378 &self,
1379 cx: &'a AppContext,
1380 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1381 self.worktree_store.read(cx).worktrees()
1382 }
1383
1384 /// Collect all user-visible worktrees, the ones that appear in the project panel.
1385 pub fn visible_worktrees<'a>(
1386 &'a self,
1387 cx: &'a AppContext,
1388 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1389 self.worktree_store.read(cx).visible_worktrees(cx)
1390 }
1391
1392 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1393 self.visible_worktrees(cx)
1394 .map(|tree| tree.read(cx).root_name())
1395 }
1396
1397 pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
1398 self.worktree_store.read(cx).worktree_for_id(id, cx)
1399 }
1400
1401 pub fn worktree_for_entry(
1402 &self,
1403 entry_id: ProjectEntryId,
1404 cx: &AppContext,
1405 ) -> Option<Model<Worktree>> {
1406 self.worktree_store
1407 .read(cx)
1408 .worktree_for_entry(entry_id, cx)
1409 }
1410
1411 pub fn worktree_id_for_entry(
1412 &self,
1413 entry_id: ProjectEntryId,
1414 cx: &AppContext,
1415 ) -> Option<WorktreeId> {
1416 self.worktree_for_entry(entry_id, cx)
1417 .map(|worktree| worktree.read(cx).id())
1418 }
1419
1420 /// Checks if the entry is the root of a worktree.
1421 pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &AppContext) -> bool {
1422 self.worktree_for_entry(entry_id, cx)
1423 .map(|worktree| {
1424 worktree
1425 .read(cx)
1426 .root_entry()
1427 .is_some_and(|e| e.id == entry_id)
1428 })
1429 .unwrap_or(false)
1430 }
1431
1432 pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &AppContext) -> Option<bool> {
1433 paths
1434 .iter()
1435 .map(|path| self.visibility_for_path(path, cx))
1436 .max()
1437 .flatten()
1438 }
1439
1440 pub fn visibility_for_path(&self, path: &Path, cx: &AppContext) -> Option<bool> {
1441 self.worktrees(cx)
1442 .filter_map(|worktree| {
1443 let worktree = worktree.read(cx);
1444 worktree
1445 .as_local()?
1446 .contains_abs_path(path)
1447 .then(|| worktree.is_visible())
1448 })
1449 .max()
1450 }
1451
1452 pub fn create_entry(
1453 &mut self,
1454 project_path: impl Into<ProjectPath>,
1455 is_directory: bool,
1456 cx: &mut ModelContext<Self>,
1457 ) -> Task<Result<CreatedEntry>> {
1458 let project_path = project_path.into();
1459 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1460 return Task::ready(Err(anyhow!(format!(
1461 "No worktree for path {project_path:?}"
1462 ))));
1463 };
1464 worktree.update(cx, |worktree, cx| {
1465 worktree.create_entry(project_path.path, is_directory, cx)
1466 })
1467 }
1468
1469 pub fn copy_entry(
1470 &mut self,
1471 entry_id: ProjectEntryId,
1472 relative_worktree_source_path: Option<PathBuf>,
1473 new_path: impl Into<Arc<Path>>,
1474 cx: &mut ModelContext<Self>,
1475 ) -> Task<Result<Option<Entry>>> {
1476 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1477 return Task::ready(Ok(None));
1478 };
1479 worktree.update(cx, |worktree, cx| {
1480 worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1481 })
1482 }
1483
1484 pub fn rename_entry(
1485 &mut self,
1486 entry_id: ProjectEntryId,
1487 new_path: impl Into<Arc<Path>>,
1488 cx: &mut ModelContext<Self>,
1489 ) -> Task<Result<CreatedEntry>> {
1490 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1491 return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1492 };
1493 worktree.update(cx, |worktree, cx| {
1494 worktree.rename_entry(entry_id, new_path, cx)
1495 })
1496 }
1497
1498 pub fn delete_entry(
1499 &mut self,
1500 entry_id: ProjectEntryId,
1501 trash: bool,
1502 cx: &mut ModelContext<Self>,
1503 ) -> Option<Task<Result<()>>> {
1504 let worktree = self.worktree_for_entry(entry_id, cx)?;
1505 worktree.update(cx, |worktree, cx| {
1506 worktree.delete_entry(entry_id, trash, cx)
1507 })
1508 }
1509
1510 pub fn expand_entry(
1511 &mut self,
1512 worktree_id: WorktreeId,
1513 entry_id: ProjectEntryId,
1514 cx: &mut ModelContext<Self>,
1515 ) -> Option<Task<Result<()>>> {
1516 let worktree = self.worktree_for_id(worktree_id, cx)?;
1517 worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1518 }
1519
1520 pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1521 if !matches!(self.client_state, ProjectClientState::Local) {
1522 if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1523 if *in_room || self.dev_server_project_id.is_none() {
1524 return Err(anyhow!("project was already shared"));
1525 } else {
1526 *in_room = true;
1527 return Ok(());
1528 }
1529 } else {
1530 return Err(anyhow!("project was already shared"));
1531 }
1532 }
1533 self.client_subscriptions.extend([
1534 self.client
1535 .subscribe_to_entity(project_id)?
1536 .set_model(&cx.handle(), &mut cx.to_async()),
1537 self.client
1538 .subscribe_to_entity(project_id)?
1539 .set_model(&self.worktree_store, &mut cx.to_async()),
1540 self.client
1541 .subscribe_to_entity(project_id)?
1542 .set_model(&self.buffer_store, &mut cx.to_async()),
1543 self.client
1544 .subscribe_to_entity(project_id)?
1545 .set_model(&self.lsp_store, &mut cx.to_async()),
1546 self.client
1547 .subscribe_to_entity(project_id)?
1548 .set_model(&self.settings_observer, &mut cx.to_async()),
1549 ]);
1550
1551 self.buffer_store.update(cx, |buffer_store, cx| {
1552 buffer_store.shared(project_id, self.client.clone().into(), cx)
1553 });
1554 self.worktree_store.update(cx, |worktree_store, cx| {
1555 worktree_store.shared(project_id, self.client.clone().into(), cx);
1556 });
1557 self.lsp_store.update(cx, |lsp_store, cx| {
1558 lsp_store.shared(project_id, self.client.clone().into(), cx)
1559 });
1560 self.task_store.update(cx, |task_store, cx| {
1561 task_store.shared(project_id, self.client.clone().into(), cx);
1562 });
1563 self.settings_observer.update(cx, |settings_observer, cx| {
1564 settings_observer.shared(project_id, self.client.clone().into(), cx)
1565 });
1566
1567 self.client_state = ProjectClientState::Shared {
1568 remote_id: project_id,
1569 };
1570
1571 cx.emit(Event::RemoteIdChanged(Some(project_id)));
1572 cx.notify();
1573 Ok(())
1574 }
1575
1576 pub fn reshared(
1577 &mut self,
1578 message: proto::ResharedProject,
1579 cx: &mut ModelContext<Self>,
1580 ) -> Result<()> {
1581 self.buffer_store
1582 .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
1583 self.set_collaborators_from_proto(message.collaborators, cx)?;
1584
1585 self.worktree_store.update(cx, |worktree_store, cx| {
1586 worktree_store.send_project_updates(cx);
1587 });
1588 cx.notify();
1589 cx.emit(Event::Reshared);
1590 Ok(())
1591 }
1592
1593 pub fn rejoined(
1594 &mut self,
1595 message: proto::RejoinedProject,
1596 message_id: u32,
1597 cx: &mut ModelContext<Self>,
1598 ) -> Result<()> {
1599 cx.update_global::<SettingsStore, _>(|store, cx| {
1600 self.worktree_store.update(cx, |worktree_store, cx| {
1601 for worktree in worktree_store.worktrees() {
1602 store
1603 .clear_local_settings(worktree.read(cx).id(), cx)
1604 .log_err();
1605 }
1606 });
1607 });
1608
1609 self.join_project_response_message_id = message_id;
1610 self.set_worktrees_from_proto(message.worktrees, cx)?;
1611 self.set_collaborators_from_proto(message.collaborators, cx)?;
1612 self.lsp_store.update(cx, |lsp_store, _| {
1613 lsp_store.set_language_server_statuses_from_proto(message.language_servers)
1614 });
1615 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
1616 .unwrap();
1617 cx.emit(Event::Rejoined);
1618 cx.notify();
1619 Ok(())
1620 }
1621
1622 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1623 self.unshare_internal(cx)?;
1624 cx.notify();
1625 Ok(())
1626 }
1627
1628 fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1629 if self.is_via_collab() {
1630 if self.dev_server_project_id().is_some() {
1631 if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1632 *in_room = false
1633 }
1634 return Ok(());
1635 } else {
1636 return Err(anyhow!("attempted to unshare a remote project"));
1637 }
1638 }
1639
1640 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
1641 self.client_state = ProjectClientState::Local;
1642 self.collaborators.clear();
1643 self.client_subscriptions.clear();
1644 self.worktree_store.update(cx, |store, cx| {
1645 store.unshared(cx);
1646 });
1647 self.buffer_store.update(cx, |buffer_store, cx| {
1648 buffer_store.forget_shared_buffers();
1649 buffer_store.unshared(cx)
1650 });
1651 self.task_store.update(cx, |task_store, cx| {
1652 task_store.unshared(cx);
1653 });
1654 self.settings_observer.update(cx, |settings_observer, cx| {
1655 settings_observer.unshared(cx);
1656 });
1657
1658 self.client
1659 .send(proto::UnshareProject {
1660 project_id: remote_id,
1661 })
1662 .ok();
1663 Ok(())
1664 } else {
1665 Err(anyhow!("attempted to unshare an unshared project"))
1666 }
1667 }
1668
1669 pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1670 if self.is_disconnected(cx) {
1671 return;
1672 }
1673 self.disconnected_from_host_internal(cx);
1674 cx.emit(Event::DisconnectedFromHost);
1675 cx.notify();
1676 }
1677
1678 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut ModelContext<Self>) {
1679 let new_capability =
1680 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
1681 Capability::ReadWrite
1682 } else {
1683 Capability::ReadOnly
1684 };
1685 if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
1686 if *capability == new_capability {
1687 return;
1688 }
1689
1690 *capability = new_capability;
1691 for buffer in self.opened_buffers(cx) {
1692 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
1693 }
1694 }
1695 }
1696
1697 fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1698 if let ProjectClientState::Remote {
1699 sharing_has_stopped,
1700 ..
1701 } = &mut self.client_state
1702 {
1703 *sharing_has_stopped = true;
1704 self.collaborators.clear();
1705 self.worktree_store.update(cx, |store, cx| {
1706 store.disconnected_from_host(cx);
1707 });
1708 self.buffer_store.update(cx, |buffer_store, cx| {
1709 buffer_store.disconnected_from_host(cx)
1710 });
1711 self.lsp_store
1712 .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
1713 }
1714 }
1715
1716 pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1717 cx.emit(Event::Closed);
1718 }
1719
1720 pub fn is_disconnected(&self, cx: &AppContext) -> bool {
1721 match &self.client_state {
1722 ProjectClientState::Remote {
1723 sharing_has_stopped,
1724 ..
1725 } => *sharing_has_stopped,
1726 ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
1727 _ => false,
1728 }
1729 }
1730
1731 fn ssh_is_disconnected(&self, cx: &AppContext) -> bool {
1732 self.ssh_client
1733 .as_ref()
1734 .map(|ssh| ssh.read(cx).is_disconnected())
1735 .unwrap_or(false)
1736 }
1737
1738 pub fn capability(&self) -> Capability {
1739 match &self.client_state {
1740 ProjectClientState::Remote { capability, .. } => *capability,
1741 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
1742 }
1743 }
1744
1745 pub fn is_read_only(&self, cx: &AppContext) -> bool {
1746 self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
1747 }
1748
1749 pub fn is_local(&self) -> bool {
1750 match &self.client_state {
1751 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1752 self.ssh_client.is_none()
1753 }
1754 ProjectClientState::Remote { .. } => false,
1755 }
1756 }
1757
1758 pub fn is_via_ssh(&self) -> bool {
1759 match &self.client_state {
1760 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1761 self.ssh_client.is_some()
1762 }
1763 ProjectClientState::Remote { .. } => false,
1764 }
1765 }
1766
1767 pub fn is_via_collab(&self) -> bool {
1768 match &self.client_state {
1769 ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
1770 ProjectClientState::Remote { .. } => true,
1771 }
1772 }
1773
1774 pub fn create_buffer(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Model<Buffer>>> {
1775 self.buffer_store
1776 .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
1777 }
1778
1779 pub fn create_local_buffer(
1780 &mut self,
1781 text: &str,
1782 language: Option<Arc<Language>>,
1783 cx: &mut ModelContext<Self>,
1784 ) -> Model<Buffer> {
1785 if self.is_via_collab() || self.is_via_ssh() {
1786 panic!("called create_local_buffer on a remote project")
1787 }
1788 self.buffer_store.update(cx, |buffer_store, cx| {
1789 buffer_store.create_local_buffer(text, language, cx)
1790 })
1791 }
1792
1793 pub fn open_path(
1794 &mut self,
1795 path: ProjectPath,
1796 cx: &mut ModelContext<Self>,
1797 ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
1798 let task = self.open_buffer(path.clone(), cx);
1799 cx.spawn(move |_, cx| async move {
1800 let buffer = task.await?;
1801 let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1802 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1803 })?;
1804
1805 let buffer: &AnyModel = &buffer;
1806 Ok((project_entry_id, buffer.clone()))
1807 })
1808 }
1809
1810 pub fn open_local_buffer(
1811 &mut self,
1812 abs_path: impl AsRef<Path>,
1813 cx: &mut ModelContext<Self>,
1814 ) -> Task<Result<Model<Buffer>>> {
1815 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1816 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1817 } else {
1818 Task::ready(Err(anyhow!("no such path")))
1819 }
1820 }
1821
1822 pub fn open_buffer(
1823 &mut self,
1824 path: impl Into<ProjectPath>,
1825 cx: &mut ModelContext<Self>,
1826 ) -> Task<Result<Model<Buffer>>> {
1827 if (self.is_via_collab() || self.is_via_ssh()) && self.is_disconnected(cx) {
1828 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1829 }
1830
1831 self.buffer_store.update(cx, |buffer_store, cx| {
1832 buffer_store.open_buffer(path.into(), cx)
1833 })
1834 }
1835
1836 pub fn open_buffer_by_id(
1837 &mut self,
1838 id: BufferId,
1839 cx: &mut ModelContext<Self>,
1840 ) -> Task<Result<Model<Buffer>>> {
1841 if let Some(buffer) = self.buffer_for_id(id, cx) {
1842 Task::ready(Ok(buffer))
1843 } else if self.is_local() || self.is_via_ssh() {
1844 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1845 } else if let Some(project_id) = self.remote_id() {
1846 let request = self.client.request(proto::OpenBufferById {
1847 project_id,
1848 id: id.into(),
1849 });
1850 cx.spawn(move |this, mut cx| async move {
1851 let buffer_id = BufferId::new(request.await?.buffer_id)?;
1852 this.update(&mut cx, |this, cx| {
1853 this.wait_for_remote_buffer(buffer_id, cx)
1854 })?
1855 .await
1856 })
1857 } else {
1858 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1859 }
1860 }
1861
1862 pub fn save_buffers(
1863 &self,
1864 buffers: HashSet<Model<Buffer>>,
1865 cx: &mut ModelContext<Self>,
1866 ) -> Task<Result<()>> {
1867 cx.spawn(move |this, mut cx| async move {
1868 let save_tasks = buffers.into_iter().filter_map(|buffer| {
1869 this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
1870 .ok()
1871 });
1872 try_join_all(save_tasks).await?;
1873 Ok(())
1874 })
1875 }
1876
1877 pub fn save_buffer(
1878 &self,
1879 buffer: Model<Buffer>,
1880 cx: &mut ModelContext<Self>,
1881 ) -> Task<Result<()>> {
1882 self.buffer_store
1883 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
1884 }
1885
1886 pub fn save_buffer_as(
1887 &mut self,
1888 buffer: Model<Buffer>,
1889 path: ProjectPath,
1890 cx: &mut ModelContext<Self>,
1891 ) -> Task<Result<()>> {
1892 self.buffer_store.update(cx, |buffer_store, cx| {
1893 buffer_store.save_buffer_as(buffer.clone(), path, cx)
1894 })
1895 }
1896
1897 pub fn get_open_buffer(
1898 &mut self,
1899 path: &ProjectPath,
1900 cx: &mut ModelContext<Self>,
1901 ) -> Option<Model<Buffer>> {
1902 self.buffer_store.read(cx).get_by_path(path, cx)
1903 }
1904
1905 fn register_buffer(
1906 &mut self,
1907 buffer: &Model<Buffer>,
1908 cx: &mut ModelContext<Self>,
1909 ) -> Result<()> {
1910 {
1911 let mut remotely_created_models = self.remotely_created_models.lock();
1912 if remotely_created_models.retain_count > 0 {
1913 remotely_created_models.buffers.push(buffer.clone())
1914 }
1915 }
1916
1917 self.request_buffer_diff_recalculation(buffer, cx);
1918
1919 cx.subscribe(buffer, |this, buffer, event, cx| {
1920 this.on_buffer_event(buffer, event, cx);
1921 })
1922 .detach();
1923
1924 Ok(())
1925 }
1926
1927 async fn send_buffer_ordered_messages(
1928 this: WeakModel<Self>,
1929 rx: UnboundedReceiver<BufferOrderedMessage>,
1930 mut cx: AsyncAppContext,
1931 ) -> Result<()> {
1932 const MAX_BATCH_SIZE: usize = 128;
1933
1934 let mut operations_by_buffer_id = HashMap::default();
1935 async fn flush_operations(
1936 this: &WeakModel<Project>,
1937 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
1938 needs_resync_with_host: &mut bool,
1939 is_local: bool,
1940 cx: &mut AsyncAppContext,
1941 ) -> Result<()> {
1942 for (buffer_id, operations) in operations_by_buffer_id.drain() {
1943 let request = this.update(cx, |this, _| {
1944 let project_id = this.remote_id()?;
1945 Some(this.client.request(proto::UpdateBuffer {
1946 buffer_id: buffer_id.into(),
1947 project_id,
1948 operations,
1949 }))
1950 })?;
1951 if let Some(request) = request {
1952 if request.await.is_err() && !is_local {
1953 *needs_resync_with_host = true;
1954 break;
1955 }
1956 }
1957 }
1958 Ok(())
1959 }
1960
1961 let mut needs_resync_with_host = false;
1962 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
1963
1964 while let Some(changes) = changes.next().await {
1965 let is_local = this.update(&mut cx, |this, _| this.is_local())?;
1966
1967 for change in changes {
1968 match change {
1969 BufferOrderedMessage::Operation {
1970 buffer_id,
1971 operation,
1972 } => {
1973 if needs_resync_with_host {
1974 continue;
1975 }
1976
1977 operations_by_buffer_id
1978 .entry(buffer_id)
1979 .or_insert(Vec::new())
1980 .push(operation);
1981 }
1982
1983 BufferOrderedMessage::Resync => {
1984 operations_by_buffer_id.clear();
1985 if this
1986 .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
1987 .await
1988 .is_ok()
1989 {
1990 needs_resync_with_host = false;
1991 }
1992 }
1993
1994 BufferOrderedMessage::LanguageServerUpdate {
1995 language_server_id,
1996 message,
1997 } => {
1998 flush_operations(
1999 &this,
2000 &mut operations_by_buffer_id,
2001 &mut needs_resync_with_host,
2002 is_local,
2003 &mut cx,
2004 )
2005 .await?;
2006
2007 this.update(&mut cx, |this, _| {
2008 if let Some(project_id) = this.remote_id() {
2009 this.client
2010 .send(proto::UpdateLanguageServer {
2011 project_id,
2012 language_server_id: language_server_id.0 as u64,
2013 variant: Some(message),
2014 })
2015 .log_err();
2016 }
2017 })?;
2018 }
2019 }
2020 }
2021
2022 flush_operations(
2023 &this,
2024 &mut operations_by_buffer_id,
2025 &mut needs_resync_with_host,
2026 is_local,
2027 &mut cx,
2028 )
2029 .await?;
2030 }
2031
2032 Ok(())
2033 }
2034
2035 fn on_buffer_store_event(
2036 &mut self,
2037 _: Model<BufferStore>,
2038 event: &BufferStoreEvent,
2039 cx: &mut ModelContext<Self>,
2040 ) {
2041 match event {
2042 BufferStoreEvent::BufferAdded(buffer) => {
2043 self.register_buffer(buffer, cx).log_err();
2044 }
2045 BufferStoreEvent::BufferChangedFilePath { .. } => {}
2046 BufferStoreEvent::BufferDropped(buffer_id) => {
2047 if let Some(ref ssh_client) = self.ssh_client {
2048 ssh_client
2049 .read(cx)
2050 .to_proto_client()
2051 .send(proto::CloseBuffer {
2052 project_id: 0,
2053 buffer_id: buffer_id.to_proto(),
2054 })
2055 .log_err();
2056 }
2057 }
2058 }
2059 }
2060
2061 fn on_lsp_store_event(
2062 &mut self,
2063 _: Model<LspStore>,
2064 event: &LspStoreEvent,
2065 cx: &mut ModelContext<Self>,
2066 ) {
2067 match event {
2068 LspStoreEvent::DiagnosticsUpdated {
2069 language_server_id,
2070 path,
2071 } => cx.emit(Event::DiagnosticsUpdated {
2072 path: path.clone(),
2073 language_server_id: *language_server_id,
2074 }),
2075 LspStoreEvent::LanguageServerAdded(language_server_id) => {
2076 cx.emit(Event::LanguageServerAdded(*language_server_id))
2077 }
2078 LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2079 cx.emit(Event::LanguageServerRemoved(*language_server_id))
2080 }
2081 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2082 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2083 ),
2084 LspStoreEvent::LanguageDetected {
2085 buffer,
2086 new_language,
2087 } => {
2088 let Some(_) = new_language else {
2089 cx.emit(Event::LanguageNotFound(buffer.clone()));
2090 return;
2091 };
2092 }
2093 LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2094 LspStoreEvent::LanguageServerPrompt(prompt) => {
2095 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2096 }
2097 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2098 cx.emit(Event::DiskBasedDiagnosticsStarted {
2099 language_server_id: *language_server_id,
2100 });
2101 }
2102 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2103 cx.emit(Event::DiskBasedDiagnosticsFinished {
2104 language_server_id: *language_server_id,
2105 });
2106 }
2107 LspStoreEvent::LanguageServerUpdate {
2108 language_server_id,
2109 message,
2110 } => {
2111 if self.is_local() {
2112 self.enqueue_buffer_ordered_message(
2113 BufferOrderedMessage::LanguageServerUpdate {
2114 language_server_id: *language_server_id,
2115 message: message.clone(),
2116 },
2117 )
2118 .ok();
2119 }
2120 }
2121 LspStoreEvent::Notification(message) => cx.emit(Event::Notification(message.clone())),
2122 LspStoreEvent::SnippetEdit {
2123 buffer_id,
2124 edits,
2125 most_recent_edit,
2126 } => {
2127 if most_recent_edit.replica_id == self.replica_id() {
2128 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2129 }
2130 }
2131 }
2132 }
2133
2134 fn on_ssh_event(
2135 &mut self,
2136 _: Model<SshRemoteClient>,
2137 event: &remote::SshRemoteEvent,
2138 cx: &mut ModelContext<Self>,
2139 ) {
2140 match event {
2141 remote::SshRemoteEvent::Disconnected => {
2142 // if self.is_via_ssh() {
2143 // self.collaborators.clear();
2144 self.worktree_store.update(cx, |store, cx| {
2145 store.disconnected_from_host(cx);
2146 });
2147 self.buffer_store.update(cx, |buffer_store, cx| {
2148 buffer_store.disconnected_from_host(cx)
2149 });
2150 self.lsp_store.update(cx, |lsp_store, _cx| {
2151 lsp_store.disconnected_from_ssh_remote()
2152 });
2153 cx.emit(Event::DisconnectedFromSshRemote);
2154 }
2155 }
2156 }
2157
2158 fn on_settings_observer_event(
2159 &mut self,
2160 _: Model<SettingsObserver>,
2161 event: &SettingsObserverEvent,
2162 cx: &mut ModelContext<Self>,
2163 ) {
2164 match event {
2165 SettingsObserverEvent::LocalSettingsUpdated(error) => {
2166 cx.emit(Event::LocalSettingsUpdated(error.clone()))
2167 }
2168 }
2169 }
2170
2171 fn on_worktree_store_event(
2172 &mut self,
2173 _: Model<WorktreeStore>,
2174 event: &WorktreeStoreEvent,
2175 cx: &mut ModelContext<Self>,
2176 ) {
2177 match event {
2178 WorktreeStoreEvent::WorktreeAdded(worktree) => {
2179 self.on_worktree_added(worktree, cx);
2180 cx.emit(Event::WorktreeAdded);
2181 }
2182 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2183 self.on_worktree_removed(*id, cx);
2184 cx.emit(Event::WorktreeRemoved(*id));
2185 }
2186 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2187 WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2188 }
2189 }
2190
2191 fn on_worktree_added(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
2192 {
2193 let mut remotely_created_models = self.remotely_created_models.lock();
2194 if remotely_created_models.retain_count > 0 {
2195 remotely_created_models.worktrees.push(worktree.clone())
2196 }
2197 }
2198 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2199 cx.subscribe(worktree, |project, worktree, event, cx| match event {
2200 worktree::Event::UpdatedEntries(changes) => {
2201 cx.emit(Event::WorktreeUpdatedEntries(
2202 worktree.read(cx).id(),
2203 changes.clone(),
2204 ));
2205
2206 let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
2207 project
2208 .client()
2209 .telemetry()
2210 .report_discovered_project_events(worktree_id, changes);
2211 }
2212 worktree::Event::UpdatedGitRepositories(_) => {
2213 cx.emit(Event::WorktreeUpdatedGitRepositories);
2214 }
2215 worktree::Event::DeletedEntry(id) => cx.emit(Event::DeletedEntry(*id)),
2216 })
2217 .detach();
2218 cx.notify();
2219 }
2220
2221 fn on_worktree_removed(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
2222 if let Some(dev_server_project_id) = self.dev_server_project_id {
2223 let paths: Vec<String> = self
2224 .visible_worktrees(cx)
2225 .filter_map(|worktree| {
2226 if worktree.read(cx).id() == id_to_remove {
2227 None
2228 } else {
2229 Some(worktree.read(cx).abs_path().to_string_lossy().to_string())
2230 }
2231 })
2232 .collect();
2233 if !paths.is_empty() {
2234 let request = self.client.request(proto::UpdateDevServerProject {
2235 dev_server_project_id: dev_server_project_id.0,
2236 paths,
2237 });
2238 cx.background_executor()
2239 .spawn(request)
2240 .detach_and_log_err(cx);
2241 }
2242 return;
2243 }
2244
2245 cx.notify();
2246 }
2247
2248 fn on_buffer_event(
2249 &mut self,
2250 buffer: Model<Buffer>,
2251 event: &BufferEvent,
2252 cx: &mut ModelContext<Self>,
2253 ) -> Option<()> {
2254 if matches!(
2255 event,
2256 BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2257 ) {
2258 self.request_buffer_diff_recalculation(&buffer, cx);
2259 }
2260
2261 let buffer_id = buffer.read(cx).remote_id();
2262 match event {
2263 BufferEvent::Operation {
2264 operation,
2265 is_local: true,
2266 } => {
2267 let operation = language::proto::serialize_operation(operation);
2268
2269 if let Some(ssh) = &self.ssh_client {
2270 ssh.read(cx)
2271 .to_proto_client()
2272 .send(proto::UpdateBuffer {
2273 project_id: 0,
2274 buffer_id: buffer_id.to_proto(),
2275 operations: vec![operation.clone()],
2276 })
2277 .ok();
2278 }
2279
2280 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2281 buffer_id,
2282 operation,
2283 })
2284 .ok();
2285 }
2286
2287 _ => {}
2288 }
2289
2290 None
2291 }
2292
2293 fn request_buffer_diff_recalculation(
2294 &mut self,
2295 buffer: &Model<Buffer>,
2296 cx: &mut ModelContext<Self>,
2297 ) {
2298 self.buffers_needing_diff.insert(buffer.downgrade());
2299 let first_insertion = self.buffers_needing_diff.len() == 1;
2300
2301 let settings = ProjectSettings::get_global(cx);
2302 let delay = if let Some(delay) = settings.git.gutter_debounce {
2303 delay
2304 } else {
2305 if first_insertion {
2306 let this = cx.weak_model();
2307 cx.defer(move |cx| {
2308 if let Some(this) = this.upgrade() {
2309 this.update(cx, |this, cx| {
2310 this.recalculate_buffer_diffs(cx).detach();
2311 });
2312 }
2313 });
2314 }
2315 return;
2316 };
2317
2318 const MIN_DELAY: u64 = 50;
2319 let delay = delay.max(MIN_DELAY);
2320 let duration = Duration::from_millis(delay);
2321
2322 self.git_diff_debouncer
2323 .fire_new(duration, cx, move |this, cx| {
2324 this.recalculate_buffer_diffs(cx)
2325 });
2326 }
2327
2328 fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2329 let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2330 cx.spawn(move |this, mut cx| async move {
2331 let tasks: Vec<_> = buffers
2332 .iter()
2333 .filter_map(|buffer| {
2334 let buffer = buffer.upgrade()?;
2335 buffer
2336 .update(&mut cx, |buffer, cx| buffer.recalculate_diff(cx))
2337 .ok()
2338 .flatten()
2339 })
2340 .collect();
2341
2342 futures::future::join_all(tasks).await;
2343
2344 this.update(&mut cx, |this, cx| {
2345 if this.buffers_needing_diff.is_empty() {
2346 // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2347 for buffer in buffers {
2348 if let Some(buffer) = buffer.upgrade() {
2349 buffer.update(cx, |_, cx| cx.notify());
2350 }
2351 }
2352 } else {
2353 this.recalculate_buffer_diffs(cx).detach();
2354 }
2355 })
2356 .ok();
2357 })
2358 }
2359
2360 pub fn set_language_for_buffer(
2361 &mut self,
2362 buffer: &Model<Buffer>,
2363 new_language: Arc<Language>,
2364 cx: &mut ModelContext<Self>,
2365 ) {
2366 self.lsp_store.update(cx, |lsp_store, cx| {
2367 lsp_store.set_language_for_buffer(buffer, new_language, cx)
2368 })
2369 }
2370
2371 pub fn restart_language_servers_for_buffers(
2372 &mut self,
2373 buffers: impl IntoIterator<Item = Model<Buffer>>,
2374 cx: &mut ModelContext<Self>,
2375 ) {
2376 self.lsp_store.update(cx, |lsp_store, cx| {
2377 lsp_store.restart_language_servers_for_buffers(buffers, cx)
2378 })
2379 }
2380
2381 pub fn cancel_language_server_work_for_buffers(
2382 &mut self,
2383 buffers: impl IntoIterator<Item = Model<Buffer>>,
2384 cx: &mut ModelContext<Self>,
2385 ) {
2386 self.lsp_store.update(cx, |lsp_store, cx| {
2387 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2388 })
2389 }
2390
2391 pub fn cancel_language_server_work(
2392 &mut self,
2393 server_id: LanguageServerId,
2394 token_to_cancel: Option<String>,
2395 cx: &mut ModelContext<Self>,
2396 ) {
2397 self.lsp_store.update(cx, |lsp_store, cx| {
2398 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2399 })
2400 }
2401
2402 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2403 self.buffer_ordered_messages_tx
2404 .unbounded_send(message)
2405 .map_err(|e| anyhow!(e))
2406 }
2407
2408 pub fn language_server_statuses<'a>(
2409 &'a self,
2410 cx: &'a AppContext,
2411 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2412 self.lsp_store.read(cx).language_server_statuses()
2413 }
2414
2415 pub fn last_formatting_failure<'a>(&self, cx: &'a AppContext) -> Option<&'a str> {
2416 self.lsp_store.read(cx).last_formatting_failure()
2417 }
2418
2419 pub fn update_diagnostics(
2420 &mut self,
2421 language_server_id: LanguageServerId,
2422 params: lsp::PublishDiagnosticsParams,
2423 disk_based_sources: &[String],
2424 cx: &mut ModelContext<Self>,
2425 ) -> Result<()> {
2426 self.lsp_store.update(cx, |lsp_store, cx| {
2427 lsp_store.update_diagnostics(language_server_id, params, disk_based_sources, cx)
2428 })
2429 }
2430
2431 pub fn update_diagnostic_entries(
2432 &mut self,
2433 server_id: LanguageServerId,
2434 abs_path: PathBuf,
2435 version: Option<i32>,
2436 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2437 cx: &mut ModelContext<Project>,
2438 ) -> Result<(), anyhow::Error> {
2439 self.lsp_store.update(cx, |lsp_store, cx| {
2440 lsp_store.update_diagnostic_entries(server_id, abs_path, version, diagnostics, cx)
2441 })
2442 }
2443
2444 pub fn reload_buffers(
2445 &self,
2446 buffers: HashSet<Model<Buffer>>,
2447 push_to_history: bool,
2448 cx: &mut ModelContext<Self>,
2449 ) -> Task<Result<ProjectTransaction>> {
2450 self.buffer_store.update(cx, |buffer_store, cx| {
2451 buffer_store.reload_buffers(buffers, push_to_history, cx)
2452 })
2453 }
2454
2455 pub fn format(
2456 &mut self,
2457 buffers: HashSet<Model<Buffer>>,
2458 push_to_history: bool,
2459 trigger: lsp_store::FormatTrigger,
2460 cx: &mut ModelContext<Project>,
2461 ) -> Task<anyhow::Result<ProjectTransaction>> {
2462 self.lsp_store.update(cx, |lsp_store, cx| {
2463 lsp_store.format(buffers, push_to_history, trigger, cx)
2464 })
2465 }
2466
2467 #[inline(never)]
2468 fn definition_impl(
2469 &mut self,
2470 buffer: &Model<Buffer>,
2471 position: PointUtf16,
2472 cx: &mut ModelContext<Self>,
2473 ) -> Task<Result<Vec<LocationLink>>> {
2474 self.request_lsp(
2475 buffer.clone(),
2476 LanguageServerToQuery::Primary,
2477 GetDefinition { position },
2478 cx,
2479 )
2480 }
2481 pub fn definition<T: ToPointUtf16>(
2482 &mut self,
2483 buffer: &Model<Buffer>,
2484 position: T,
2485 cx: &mut ModelContext<Self>,
2486 ) -> Task<Result<Vec<LocationLink>>> {
2487 let position = position.to_point_utf16(buffer.read(cx));
2488 self.definition_impl(buffer, position, cx)
2489 }
2490
2491 fn declaration_impl(
2492 &mut self,
2493 buffer: &Model<Buffer>,
2494 position: PointUtf16,
2495 cx: &mut ModelContext<Self>,
2496 ) -> Task<Result<Vec<LocationLink>>> {
2497 self.request_lsp(
2498 buffer.clone(),
2499 LanguageServerToQuery::Primary,
2500 GetDeclaration { position },
2501 cx,
2502 )
2503 }
2504
2505 pub fn declaration<T: ToPointUtf16>(
2506 &mut self,
2507 buffer: &Model<Buffer>,
2508 position: T,
2509 cx: &mut ModelContext<Self>,
2510 ) -> Task<Result<Vec<LocationLink>>> {
2511 let position = position.to_point_utf16(buffer.read(cx));
2512 self.declaration_impl(buffer, position, cx)
2513 }
2514
2515 fn type_definition_impl(
2516 &mut self,
2517 buffer: &Model<Buffer>,
2518 position: PointUtf16,
2519 cx: &mut ModelContext<Self>,
2520 ) -> Task<Result<Vec<LocationLink>>> {
2521 self.request_lsp(
2522 buffer.clone(),
2523 LanguageServerToQuery::Primary,
2524 GetTypeDefinition { position },
2525 cx,
2526 )
2527 }
2528
2529 pub fn type_definition<T: ToPointUtf16>(
2530 &mut self,
2531 buffer: &Model<Buffer>,
2532 position: T,
2533 cx: &mut ModelContext<Self>,
2534 ) -> Task<Result<Vec<LocationLink>>> {
2535 let position = position.to_point_utf16(buffer.read(cx));
2536 self.type_definition_impl(buffer, position, cx)
2537 }
2538
2539 pub fn implementation<T: ToPointUtf16>(
2540 &mut self,
2541 buffer: &Model<Buffer>,
2542 position: T,
2543 cx: &mut ModelContext<Self>,
2544 ) -> Task<Result<Vec<LocationLink>>> {
2545 let position = position.to_point_utf16(buffer.read(cx));
2546 self.request_lsp(
2547 buffer.clone(),
2548 LanguageServerToQuery::Primary,
2549 GetImplementation { position },
2550 cx,
2551 )
2552 }
2553
2554 pub fn references<T: ToPointUtf16>(
2555 &mut self,
2556 buffer: &Model<Buffer>,
2557 position: T,
2558 cx: &mut ModelContext<Self>,
2559 ) -> Task<Result<Vec<Location>>> {
2560 let position = position.to_point_utf16(buffer.read(cx));
2561 self.request_lsp(
2562 buffer.clone(),
2563 LanguageServerToQuery::Primary,
2564 GetReferences { position },
2565 cx,
2566 )
2567 }
2568
2569 fn document_highlights_impl(
2570 &mut self,
2571 buffer: &Model<Buffer>,
2572 position: PointUtf16,
2573 cx: &mut ModelContext<Self>,
2574 ) -> Task<Result<Vec<DocumentHighlight>>> {
2575 self.request_lsp(
2576 buffer.clone(),
2577 LanguageServerToQuery::Primary,
2578 GetDocumentHighlights { position },
2579 cx,
2580 )
2581 }
2582
2583 pub fn document_highlights<T: ToPointUtf16>(
2584 &mut self,
2585 buffer: &Model<Buffer>,
2586 position: T,
2587 cx: &mut ModelContext<Self>,
2588 ) -> Task<Result<Vec<DocumentHighlight>>> {
2589 let position = position.to_point_utf16(buffer.read(cx));
2590 self.document_highlights_impl(buffer, position, cx)
2591 }
2592
2593 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
2594 self.lsp_store
2595 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
2596 }
2597
2598 pub fn open_buffer_for_symbol(
2599 &mut self,
2600 symbol: &Symbol,
2601 cx: &mut ModelContext<Self>,
2602 ) -> Task<Result<Model<Buffer>>> {
2603 self.lsp_store.update(cx, |lsp_store, cx| {
2604 lsp_store.open_buffer_for_symbol(symbol, cx)
2605 })
2606 }
2607
2608 pub fn open_local_buffer_via_lsp(
2609 &mut self,
2610 abs_path: lsp::Url,
2611 language_server_id: LanguageServerId,
2612 language_server_name: LanguageServerName,
2613 cx: &mut ModelContext<Self>,
2614 ) -> Task<Result<Model<Buffer>>> {
2615 self.lsp_store.update(cx, |lsp_store, cx| {
2616 lsp_store.open_local_buffer_via_lsp(
2617 abs_path,
2618 language_server_id,
2619 language_server_name,
2620 cx,
2621 )
2622 })
2623 }
2624
2625 pub fn signature_help<T: ToPointUtf16>(
2626 &self,
2627 buffer: &Model<Buffer>,
2628 position: T,
2629 cx: &mut ModelContext<Self>,
2630 ) -> Task<Vec<SignatureHelp>> {
2631 self.lsp_store.update(cx, |lsp_store, cx| {
2632 lsp_store.signature_help(buffer, position, cx)
2633 })
2634 }
2635
2636 pub fn hover<T: ToPointUtf16>(
2637 &self,
2638 buffer: &Model<Buffer>,
2639 position: T,
2640 cx: &mut ModelContext<Self>,
2641 ) -> Task<Vec<Hover>> {
2642 let position = position.to_point_utf16(buffer.read(cx));
2643 self.lsp_store
2644 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
2645 }
2646
2647 pub fn linked_edit(
2648 &self,
2649 buffer: &Model<Buffer>,
2650 position: Anchor,
2651 cx: &mut ModelContext<Self>,
2652 ) -> Task<Result<Vec<Range<Anchor>>>> {
2653 self.lsp_store.update(cx, |lsp_store, cx| {
2654 lsp_store.linked_edit(buffer, position, cx)
2655 })
2656 }
2657
2658 pub fn completions<T: ToOffset + ToPointUtf16>(
2659 &self,
2660 buffer: &Model<Buffer>,
2661 position: T,
2662 context: CompletionContext,
2663 cx: &mut ModelContext<Self>,
2664 ) -> Task<Result<Vec<Completion>>> {
2665 let position = position.to_point_utf16(buffer.read(cx));
2666 self.lsp_store.update(cx, |lsp_store, cx| {
2667 lsp_store.completions(buffer, position, context, cx)
2668 })
2669 }
2670
2671 pub fn resolve_completions(
2672 &self,
2673 buffer: Model<Buffer>,
2674 completion_indices: Vec<usize>,
2675 completions: Arc<RwLock<Box<[Completion]>>>,
2676 cx: &mut ModelContext<Self>,
2677 ) -> Task<Result<bool>> {
2678 self.lsp_store.update(cx, |lsp_store, cx| {
2679 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
2680 })
2681 }
2682
2683 pub fn apply_additional_edits_for_completion(
2684 &self,
2685 buffer_handle: Model<Buffer>,
2686 completion: Completion,
2687 push_to_history: bool,
2688 cx: &mut ModelContext<Self>,
2689 ) -> Task<Result<Option<Transaction>>> {
2690 self.lsp_store.update(cx, |lsp_store, cx| {
2691 lsp_store.apply_additional_edits_for_completion(
2692 buffer_handle,
2693 completion,
2694 push_to_history,
2695 cx,
2696 )
2697 })
2698 }
2699
2700 pub fn code_actions<T: Clone + ToOffset>(
2701 &mut self,
2702 buffer_handle: &Model<Buffer>,
2703 range: Range<T>,
2704 cx: &mut ModelContext<Self>,
2705 ) -> Task<Result<Vec<CodeAction>>> {
2706 let buffer = buffer_handle.read(cx);
2707 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2708 self.lsp_store.update(cx, |lsp_store, cx| {
2709 lsp_store.code_actions(buffer_handle, range, cx)
2710 })
2711 }
2712
2713 pub fn apply_code_action(
2714 &self,
2715 buffer_handle: Model<Buffer>,
2716 action: CodeAction,
2717 push_to_history: bool,
2718 cx: &mut ModelContext<Self>,
2719 ) -> Task<Result<ProjectTransaction>> {
2720 self.lsp_store.update(cx, |lsp_store, cx| {
2721 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
2722 })
2723 }
2724
2725 fn prepare_rename_impl(
2726 &mut self,
2727 buffer: Model<Buffer>,
2728 position: PointUtf16,
2729 cx: &mut ModelContext<Self>,
2730 ) -> Task<Result<Option<Range<Anchor>>>> {
2731 self.request_lsp(
2732 buffer,
2733 LanguageServerToQuery::Primary,
2734 PrepareRename { position },
2735 cx,
2736 )
2737 }
2738 pub fn prepare_rename<T: ToPointUtf16>(
2739 &mut self,
2740 buffer: Model<Buffer>,
2741 position: T,
2742 cx: &mut ModelContext<Self>,
2743 ) -> Task<Result<Option<Range<Anchor>>>> {
2744 let position = position.to_point_utf16(buffer.read(cx));
2745 self.prepare_rename_impl(buffer, position, cx)
2746 }
2747
2748 fn perform_rename_impl(
2749 &mut self,
2750 buffer: Model<Buffer>,
2751 position: PointUtf16,
2752 new_name: String,
2753 push_to_history: bool,
2754 cx: &mut ModelContext<Self>,
2755 ) -> Task<Result<ProjectTransaction>> {
2756 let position = position.to_point_utf16(buffer.read(cx));
2757 self.request_lsp(
2758 buffer,
2759 LanguageServerToQuery::Primary,
2760 PerformRename {
2761 position,
2762 new_name,
2763 push_to_history,
2764 },
2765 cx,
2766 )
2767 }
2768
2769 pub fn perform_rename<T: ToPointUtf16>(
2770 &mut self,
2771 buffer: Model<Buffer>,
2772 position: T,
2773 new_name: String,
2774 cx: &mut ModelContext<Self>,
2775 ) -> Task<Result<ProjectTransaction>> {
2776 let position = position.to_point_utf16(buffer.read(cx));
2777 self.perform_rename_impl(buffer, position, new_name, true, cx)
2778 }
2779
2780 pub fn on_type_format<T: ToPointUtf16>(
2781 &mut self,
2782 buffer: Model<Buffer>,
2783 position: T,
2784 trigger: String,
2785 push_to_history: bool,
2786 cx: &mut ModelContext<Self>,
2787 ) -> Task<Result<Option<Transaction>>> {
2788 self.lsp_store.update(cx, |lsp_store, cx| {
2789 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
2790 })
2791 }
2792
2793 pub fn inlay_hints<T: ToOffset>(
2794 &mut self,
2795 buffer_handle: Model<Buffer>,
2796 range: Range<T>,
2797 cx: &mut ModelContext<Self>,
2798 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
2799 let buffer = buffer_handle.read(cx);
2800 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2801 self.lsp_store.update(cx, |lsp_store, cx| {
2802 lsp_store.inlay_hints(buffer_handle, range, cx)
2803 })
2804 }
2805
2806 pub fn resolve_inlay_hint(
2807 &self,
2808 hint: InlayHint,
2809 buffer_handle: Model<Buffer>,
2810 server_id: LanguageServerId,
2811 cx: &mut ModelContext<Self>,
2812 ) -> Task<anyhow::Result<InlayHint>> {
2813 self.lsp_store.update(cx, |lsp_store, cx| {
2814 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
2815 })
2816 }
2817
2818 pub fn search(
2819 &mut self,
2820 query: SearchQuery,
2821 cx: &mut ModelContext<Self>,
2822 ) -> Receiver<SearchResult> {
2823 let (result_tx, result_rx) = smol::channel::unbounded();
2824
2825 let matching_buffers_rx = if query.is_opened_only() {
2826 self.sort_search_candidates(&query, cx)
2827 } else {
2828 self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
2829 };
2830
2831 cx.spawn(|_, cx| async move {
2832 let mut range_count = 0;
2833 let mut buffer_count = 0;
2834 let mut limit_reached = false;
2835 let query = Arc::new(query);
2836 let mut chunks = matching_buffers_rx.ready_chunks(64);
2837
2838 // Now that we know what paths match the query, we will load at most
2839 // 64 buffers at a time to avoid overwhelming the main thread. For each
2840 // opened buffer, we will spawn a background task that retrieves all the
2841 // ranges in the buffer matched by the query.
2842 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
2843 let mut chunk_results = Vec::new();
2844 for buffer in matching_buffer_chunk {
2845 let buffer = buffer.clone();
2846 let query = query.clone();
2847 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
2848 chunk_results.push(cx.background_executor().spawn(async move {
2849 let ranges = query
2850 .search(&snapshot, None)
2851 .await
2852 .iter()
2853 .map(|range| {
2854 snapshot.anchor_before(range.start)
2855 ..snapshot.anchor_after(range.end)
2856 })
2857 .collect::<Vec<_>>();
2858 anyhow::Ok((buffer, ranges))
2859 }));
2860 }
2861
2862 let chunk_results = futures::future::join_all(chunk_results).await;
2863 for result in chunk_results {
2864 if let Some((buffer, ranges)) = result.log_err() {
2865 range_count += ranges.len();
2866 buffer_count += 1;
2867 result_tx
2868 .send(SearchResult::Buffer { buffer, ranges })
2869 .await?;
2870 if buffer_count > MAX_SEARCH_RESULT_FILES
2871 || range_count > MAX_SEARCH_RESULT_RANGES
2872 {
2873 limit_reached = true;
2874 break 'outer;
2875 }
2876 }
2877 }
2878 }
2879
2880 if limit_reached {
2881 result_tx.send(SearchResult::LimitReached).await?;
2882 }
2883
2884 anyhow::Ok(())
2885 })
2886 .detach();
2887
2888 result_rx
2889 }
2890
2891 fn find_search_candidate_buffers(
2892 &mut self,
2893 query: &SearchQuery,
2894 limit: usize,
2895 cx: &mut ModelContext<Project>,
2896 ) -> Receiver<Model<Buffer>> {
2897 if self.is_local() {
2898 let fs = self.fs.clone();
2899 self.buffer_store.update(cx, |buffer_store, cx| {
2900 buffer_store.find_search_candidates(query, limit, fs, cx)
2901 })
2902 } else {
2903 self.find_search_candidates_remote(query, limit, cx)
2904 }
2905 }
2906
2907 fn sort_search_candidates(
2908 &mut self,
2909 search_query: &SearchQuery,
2910 cx: &mut ModelContext<Project>,
2911 ) -> Receiver<Model<Buffer>> {
2912 let worktree_store = self.worktree_store.read(cx);
2913 let mut buffers = search_query
2914 .buffers()
2915 .into_iter()
2916 .flatten()
2917 .filter(|buffer| {
2918 let b = buffer.read(cx);
2919 if let Some(file) = b.file() {
2920 if !search_query.file_matches(file.path()) {
2921 return false;
2922 }
2923 if let Some(entry) = b
2924 .entry_id(cx)
2925 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
2926 {
2927 if entry.is_ignored && !search_query.include_ignored() {
2928 return false;
2929 }
2930 }
2931 }
2932 true
2933 })
2934 .collect::<Vec<_>>();
2935 let (tx, rx) = smol::channel::unbounded();
2936 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
2937 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
2938 (None, Some(_)) => std::cmp::Ordering::Less,
2939 (Some(_), None) => std::cmp::Ordering::Greater,
2940 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
2941 });
2942 for buffer in buffers {
2943 tx.send_blocking(buffer.clone()).unwrap()
2944 }
2945
2946 rx
2947 }
2948
2949 fn find_search_candidates_remote(
2950 &mut self,
2951 query: &SearchQuery,
2952 limit: usize,
2953 cx: &mut ModelContext<Project>,
2954 ) -> Receiver<Model<Buffer>> {
2955 let (tx, rx) = smol::channel::unbounded();
2956
2957 let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
2958 (ssh_client.read(cx).to_proto_client(), 0)
2959 } else if let Some(remote_id) = self.remote_id() {
2960 (self.client.clone().into(), remote_id)
2961 } else {
2962 return rx;
2963 };
2964
2965 let request = client.request(proto::FindSearchCandidates {
2966 project_id: remote_id,
2967 query: Some(query.to_proto()),
2968 limit: limit as _,
2969 });
2970 let guard = self.retain_remotely_created_models(cx);
2971
2972 cx.spawn(move |this, mut cx| async move {
2973 let response = request.await?;
2974 for buffer_id in response.buffer_ids {
2975 let buffer_id = BufferId::new(buffer_id)?;
2976 let buffer = this
2977 .update(&mut cx, |this, cx| {
2978 this.wait_for_remote_buffer(buffer_id, cx)
2979 })?
2980 .await?;
2981 let _ = tx.send(buffer).await;
2982 }
2983
2984 drop(guard);
2985 anyhow::Ok(())
2986 })
2987 .detach_and_log_err(cx);
2988 rx
2989 }
2990
2991 pub fn request_lsp<R: LspCommand>(
2992 &mut self,
2993 buffer_handle: Model<Buffer>,
2994 server: LanguageServerToQuery,
2995 request: R,
2996 cx: &mut ModelContext<Self>,
2997 ) -> Task<Result<R::Response>>
2998 where
2999 <R::LspRequest as lsp::request::Request>::Result: Send,
3000 <R::LspRequest as lsp::request::Request>::Params: Send,
3001 {
3002 let guard = self.retain_remotely_created_models(cx);
3003 let task = self.lsp_store.update(cx, |lsp_store, cx| {
3004 lsp_store.request_lsp(buffer_handle, server, request, cx)
3005 });
3006 cx.spawn(|_, _| async move {
3007 let result = task.await;
3008 drop(guard);
3009 result
3010 })
3011 }
3012
3013 /// Move a worktree to a new position in the worktree order.
3014 ///
3015 /// The worktree will moved to the opposite side of the destination worktree.
3016 ///
3017 /// # Example
3018 ///
3019 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3020 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3021 ///
3022 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3023 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3024 ///
3025 /// # Errors
3026 ///
3027 /// An error will be returned if the worktree or destination worktree are not found.
3028 pub fn move_worktree(
3029 &mut self,
3030 source: WorktreeId,
3031 destination: WorktreeId,
3032 cx: &mut ModelContext<'_, Self>,
3033 ) -> Result<()> {
3034 self.worktree_store.update(cx, |worktree_store, cx| {
3035 worktree_store.move_worktree(source, destination, cx)
3036 })
3037 }
3038
3039 pub fn find_or_create_worktree(
3040 &mut self,
3041 abs_path: impl AsRef<Path>,
3042 visible: bool,
3043 cx: &mut ModelContext<Self>,
3044 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
3045 let abs_path = abs_path.as_ref();
3046 if let Some((tree, relative_path)) = self.find_worktree(abs_path, cx) {
3047 Task::ready(Ok((tree, relative_path)))
3048 } else {
3049 let worktree = self.create_worktree(abs_path, visible, cx);
3050 cx.background_executor()
3051 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
3052 }
3053 }
3054
3055 pub fn find_worktree(
3056 &self,
3057 abs_path: &Path,
3058 cx: &AppContext,
3059 ) -> Option<(Model<Worktree>, PathBuf)> {
3060 self.worktree_store.read_with(cx, |worktree_store, cx| {
3061 worktree_store.find_worktree(abs_path, cx)
3062 })
3063 }
3064
3065 pub fn is_shared(&self) -> bool {
3066 match &self.client_state {
3067 ProjectClientState::Shared { .. } => true,
3068 ProjectClientState::Local => false,
3069 ProjectClientState::Remote { in_room, .. } => *in_room,
3070 }
3071 }
3072
3073 // Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3074 pub fn resolve_existing_file_path(
3075 &self,
3076 path: &str,
3077 buffer: &Model<Buffer>,
3078 cx: &mut ModelContext<Self>,
3079 ) -> Task<Option<ResolvedPath>> {
3080 let path_buf = PathBuf::from(path);
3081 if path_buf.is_absolute() || path.starts_with("~") {
3082 if self.is_local() {
3083 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3084
3085 let fs = self.fs.clone();
3086 cx.background_executor().spawn(async move {
3087 let path = expanded.as_path();
3088 let exists = fs.is_file(path).await;
3089
3090 exists.then(|| ResolvedPath::AbsPath(expanded))
3091 })
3092 } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3093 let request =
3094 ssh_client
3095 .read(cx)
3096 .to_proto_client()
3097 .request(proto::CheckFileExists {
3098 project_id: SSH_PROJECT_ID,
3099 path: path.to_string(),
3100 });
3101 cx.background_executor().spawn(async move {
3102 let response = request.await.log_err()?;
3103 if response.exists {
3104 Some(ResolvedPath::AbsPath(PathBuf::from(response.path)))
3105 } else {
3106 None
3107 }
3108 })
3109 } else {
3110 return Task::ready(None);
3111 }
3112 } else {
3113 self.resolve_path_in_worktrees(path_buf, buffer, cx)
3114 }
3115 }
3116
3117 fn resolve_path_in_worktrees(
3118 &self,
3119 path: PathBuf,
3120 buffer: &Model<Buffer>,
3121 cx: &mut ModelContext<Self>,
3122 ) -> Task<Option<ResolvedPath>> {
3123 let mut candidates = vec![path.clone()];
3124
3125 if let Some(file) = buffer.read(cx).file() {
3126 if let Some(dir) = file.path().parent() {
3127 let joined = dir.to_path_buf().join(path);
3128 candidates.push(joined);
3129 }
3130 }
3131
3132 let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3133 cx.spawn(|_, mut cx| async move {
3134 for worktree in worktrees {
3135 for candidate in candidates.iter() {
3136 let path = worktree
3137 .update(&mut cx, |worktree, _| {
3138 let root_entry_path = &worktree.root_entry()?.path;
3139
3140 let resolved = resolve_path(root_entry_path, candidate);
3141
3142 let stripped =
3143 resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3144
3145 worktree.entry_for_path(stripped).map(|entry| {
3146 ResolvedPath::ProjectPath(ProjectPath {
3147 worktree_id: worktree.id(),
3148 path: entry.path.clone(),
3149 })
3150 })
3151 })
3152 .ok()?;
3153
3154 if path.is_some() {
3155 return path;
3156 }
3157 }
3158 }
3159 None
3160 })
3161 }
3162
3163 pub fn list_directory(
3164 &self,
3165 query: String,
3166 cx: &mut ModelContext<Self>,
3167 ) -> Task<Result<Vec<PathBuf>>> {
3168 if self.is_local() {
3169 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3170 } else if let Some(session) = self.ssh_client.as_ref() {
3171 let request = proto::ListRemoteDirectory {
3172 dev_server_id: SSH_PROJECT_ID,
3173 path: query,
3174 };
3175
3176 let response = session.read(cx).to_proto_client().request(request);
3177 cx.background_executor().spawn(async move {
3178 let response = response.await?;
3179 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3180 })
3181 } else if let Some(dev_server) = self.dev_server_project_id().and_then(|id| {
3182 dev_server_projects::Store::global(cx)
3183 .read(cx)
3184 .dev_server_for_project(id)
3185 }) {
3186 let request = proto::ListRemoteDirectory {
3187 dev_server_id: dev_server.id.0,
3188 path: query,
3189 };
3190 let response = self.client.request(request);
3191 cx.background_executor().spawn(async move {
3192 let response = response.await?;
3193 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3194 })
3195 } else {
3196 Task::ready(Err(anyhow!("cannot list directory in remote project")))
3197 }
3198 }
3199
3200 fn create_worktree(
3201 &mut self,
3202 abs_path: impl AsRef<Path>,
3203 visible: bool,
3204 cx: &mut ModelContext<Self>,
3205 ) -> Task<Result<Model<Worktree>>> {
3206 self.worktree_store.update(cx, |worktree_store, cx| {
3207 worktree_store.create_worktree(abs_path, visible, cx)
3208 })
3209 }
3210
3211 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
3212 self.worktree_store.update(cx, |worktree_store, cx| {
3213 worktree_store.remove_worktree(id_to_remove, cx);
3214 });
3215 }
3216
3217 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
3218 self.worktree_store.update(cx, |worktree_store, cx| {
3219 worktree_store.add(worktree, cx);
3220 });
3221 }
3222
3223 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
3224 let new_active_entry = entry.and_then(|project_path| {
3225 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3226 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3227 Some(entry.id)
3228 });
3229 if new_active_entry != self.active_entry {
3230 self.active_entry = new_active_entry;
3231 self.lsp_store.update(cx, |lsp_store, _| {
3232 lsp_store.set_active_entry(new_active_entry);
3233 });
3234 cx.emit(Event::ActiveEntryChanged(new_active_entry));
3235 }
3236 }
3237
3238 pub fn language_servers_running_disk_based_diagnostics<'a>(
3239 &'a self,
3240 cx: &'a AppContext,
3241 ) -> impl Iterator<Item = LanguageServerId> + 'a {
3242 self.lsp_store
3243 .read(cx)
3244 .language_servers_running_disk_based_diagnostics()
3245 }
3246
3247 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
3248 let mut summary = DiagnosticSummary::default();
3249 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
3250 summary.error_count += path_summary.error_count;
3251 summary.warning_count += path_summary.warning_count;
3252 }
3253 summary
3254 }
3255
3256 pub fn diagnostic_summaries<'a>(
3257 &'a self,
3258 include_ignored: bool,
3259 cx: &'a AppContext,
3260 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3261 self.lsp_store
3262 .read(cx)
3263 .diagnostic_summaries(include_ignored, cx)
3264 }
3265
3266 pub fn active_entry(&self) -> Option<ProjectEntryId> {
3267 self.active_entry
3268 }
3269
3270 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
3271 self.worktree_store.read(cx).entry_for_path(path, cx)
3272 }
3273
3274 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
3275 let worktree = self.worktree_for_entry(entry_id, cx)?;
3276 let worktree = worktree.read(cx);
3277 let worktree_id = worktree.id();
3278 let path = worktree.entry_for_id(entry_id)?.path.clone();
3279 Some(ProjectPath { worktree_id, path })
3280 }
3281
3282 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
3283 let workspace_root = self
3284 .worktree_for_id(project_path.worktree_id, cx)?
3285 .read(cx)
3286 .abs_path();
3287 let project_path = project_path.path.as_ref();
3288
3289 Some(if project_path == Path::new("") {
3290 workspace_root.to_path_buf()
3291 } else {
3292 workspace_root.join(project_path)
3293 })
3294 }
3295
3296 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
3297 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
3298 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
3299 /// the first visible worktree that has an entry for that relative path.
3300 ///
3301 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
3302 /// root name from paths.
3303 ///
3304 /// # Arguments
3305 ///
3306 /// * `path` - A full path that starts with a worktree root name, or alternatively a
3307 /// relative path within a visible worktree.
3308 /// * `cx` - A reference to the `AppContext`.
3309 ///
3310 /// # Returns
3311 ///
3312 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
3313 pub fn find_project_path(&self, path: &Path, cx: &AppContext) -> Option<ProjectPath> {
3314 let worktree_store = self.worktree_store.read(cx);
3315
3316 for worktree in worktree_store.visible_worktrees(cx) {
3317 let worktree_root_name = worktree.read(cx).root_name();
3318 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
3319 return Some(ProjectPath {
3320 worktree_id: worktree.read(cx).id(),
3321 path: relative_path.into(),
3322 });
3323 }
3324 }
3325
3326 for worktree in worktree_store.visible_worktrees(cx) {
3327 let worktree = worktree.read(cx);
3328 if let Some(entry) = worktree.entry_for_path(path) {
3329 return Some(ProjectPath {
3330 worktree_id: worktree.id(),
3331 path: entry.path.clone(),
3332 });
3333 }
3334 }
3335
3336 None
3337 }
3338
3339 pub fn get_workspace_root(
3340 &self,
3341 project_path: &ProjectPath,
3342 cx: &AppContext,
3343 ) -> Option<PathBuf> {
3344 Some(
3345 self.worktree_for_id(project_path.worktree_id, cx)?
3346 .read(cx)
3347 .abs_path()
3348 .to_path_buf(),
3349 )
3350 }
3351
3352 pub fn get_repo(
3353 &self,
3354 project_path: &ProjectPath,
3355 cx: &AppContext,
3356 ) -> Option<Arc<dyn GitRepository>> {
3357 self.worktree_for_id(project_path.worktree_id, cx)?
3358 .read(cx)
3359 .as_local()?
3360 .local_git_repo(&project_path.path)
3361 }
3362
3363 pub fn get_first_worktree_root_repo(&self, cx: &AppContext) -> Option<Arc<dyn GitRepository>> {
3364 let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
3365 let root_entry = worktree.root_git_entry()?;
3366 worktree.get_local_repo(&root_entry)?.repo().clone().into()
3367 }
3368
3369 pub fn blame_buffer(
3370 &self,
3371 buffer: &Model<Buffer>,
3372 version: Option<clock::Global>,
3373 cx: &AppContext,
3374 ) -> Task<Result<Blame>> {
3375 self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
3376 }
3377
3378 // RPC message handlers
3379
3380 async fn handle_unshare_project(
3381 this: Model<Self>,
3382 _: TypedEnvelope<proto::UnshareProject>,
3383 mut cx: AsyncAppContext,
3384 ) -> Result<()> {
3385 this.update(&mut cx, |this, cx| {
3386 if this.is_local() || this.is_via_ssh() {
3387 this.unshare(cx)?;
3388 } else {
3389 this.disconnected_from_host(cx);
3390 }
3391 Ok(())
3392 })?
3393 }
3394
3395 async fn handle_add_collaborator(
3396 this: Model<Self>,
3397 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3398 mut cx: AsyncAppContext,
3399 ) -> Result<()> {
3400 let collaborator = envelope
3401 .payload
3402 .collaborator
3403 .take()
3404 .ok_or_else(|| anyhow!("empty collaborator"))?;
3405
3406 let collaborator = Collaborator::from_proto(collaborator)?;
3407 this.update(&mut cx, |this, cx| {
3408 this.buffer_store.update(cx, |buffer_store, _| {
3409 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
3410 });
3411 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
3412 this.collaborators
3413 .insert(collaborator.peer_id, collaborator);
3414 cx.notify();
3415 })?;
3416
3417 Ok(())
3418 }
3419
3420 async fn handle_update_project_collaborator(
3421 this: Model<Self>,
3422 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
3423 mut cx: AsyncAppContext,
3424 ) -> Result<()> {
3425 let old_peer_id = envelope
3426 .payload
3427 .old_peer_id
3428 .ok_or_else(|| anyhow!("missing old peer id"))?;
3429 let new_peer_id = envelope
3430 .payload
3431 .new_peer_id
3432 .ok_or_else(|| anyhow!("missing new peer id"))?;
3433 this.update(&mut cx, |this, cx| {
3434 let collaborator = this
3435 .collaborators
3436 .remove(&old_peer_id)
3437 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
3438 let is_host = collaborator.replica_id == 0;
3439 this.collaborators.insert(new_peer_id, collaborator);
3440
3441 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
3442 this.buffer_store.update(cx, |buffer_store, _| {
3443 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
3444 });
3445
3446 if is_host {
3447 this.buffer_store
3448 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
3449 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
3450 .unwrap();
3451 cx.emit(Event::HostReshared);
3452 }
3453
3454 cx.emit(Event::CollaboratorUpdated {
3455 old_peer_id,
3456 new_peer_id,
3457 });
3458 cx.notify();
3459 Ok(())
3460 })?
3461 }
3462
3463 async fn handle_remove_collaborator(
3464 this: Model<Self>,
3465 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3466 mut cx: AsyncAppContext,
3467 ) -> Result<()> {
3468 this.update(&mut cx, |this, cx| {
3469 let peer_id = envelope
3470 .payload
3471 .peer_id
3472 .ok_or_else(|| anyhow!("invalid peer id"))?;
3473 let replica_id = this
3474 .collaborators
3475 .remove(&peer_id)
3476 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3477 .replica_id;
3478 this.buffer_store.update(cx, |buffer_store, cx| {
3479 buffer_store.forget_shared_buffers_for(&peer_id);
3480 for buffer in buffer_store.buffers() {
3481 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3482 }
3483 });
3484
3485 cx.emit(Event::CollaboratorLeft(peer_id));
3486 cx.notify();
3487 Ok(())
3488 })?
3489 }
3490
3491 async fn handle_update_project(
3492 this: Model<Self>,
3493 envelope: TypedEnvelope<proto::UpdateProject>,
3494 mut cx: AsyncAppContext,
3495 ) -> Result<()> {
3496 this.update(&mut cx, |this, cx| {
3497 // Don't handle messages that were sent before the response to us joining the project
3498 if envelope.message_id > this.join_project_response_message_id {
3499 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
3500 }
3501 Ok(())
3502 })?
3503 }
3504
3505 // Collab sends UpdateWorktree protos as messages
3506 async fn handle_update_worktree(
3507 this: Model<Self>,
3508 envelope: TypedEnvelope<proto::UpdateWorktree>,
3509 mut cx: AsyncAppContext,
3510 ) -> Result<()> {
3511 this.update(&mut cx, |this, cx| {
3512 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3513 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3514 worktree.update(cx, |worktree, _| {
3515 let worktree = worktree.as_remote_mut().unwrap();
3516 worktree.update_from_remote(envelope.payload);
3517 });
3518 }
3519 Ok(())
3520 })?
3521 }
3522
3523 async fn handle_update_buffer(
3524 this: Model<Self>,
3525 envelope: TypedEnvelope<proto::UpdateBuffer>,
3526 cx: AsyncAppContext,
3527 ) -> Result<proto::Ack> {
3528 let buffer_store = this.read_with(&cx, |this, cx| {
3529 if let Some(ssh) = &this.ssh_client {
3530 let mut payload = envelope.payload.clone();
3531 payload.project_id = SSH_PROJECT_ID;
3532 cx.background_executor()
3533 .spawn(ssh.read(cx).to_proto_client().request(payload))
3534 .detach_and_log_err(cx);
3535 }
3536 this.buffer_store.clone()
3537 })?;
3538 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
3539 }
3540
3541 fn retain_remotely_created_models(
3542 &mut self,
3543 cx: &mut ModelContext<Self>,
3544 ) -> RemotelyCreatedModelGuard {
3545 {
3546 let mut remotely_create_models = self.remotely_created_models.lock();
3547 if remotely_create_models.retain_count == 0 {
3548 remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
3549 remotely_create_models.worktrees =
3550 self.worktree_store.read(cx).worktrees().collect();
3551 }
3552 remotely_create_models.retain_count += 1;
3553 }
3554 RemotelyCreatedModelGuard {
3555 remote_models: Arc::downgrade(&self.remotely_created_models),
3556 }
3557 }
3558
3559 async fn handle_create_buffer_for_peer(
3560 this: Model<Self>,
3561 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
3562 mut cx: AsyncAppContext,
3563 ) -> Result<()> {
3564 this.update(&mut cx, |this, cx| {
3565 this.buffer_store.update(cx, |buffer_store, cx| {
3566 buffer_store.handle_create_buffer_for_peer(
3567 envelope,
3568 this.replica_id(),
3569 this.capability(),
3570 cx,
3571 )
3572 })
3573 })?
3574 }
3575
3576 async fn handle_synchronize_buffers(
3577 this: Model<Self>,
3578 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
3579 mut cx: AsyncAppContext,
3580 ) -> Result<proto::SynchronizeBuffersResponse> {
3581 let response = this.update(&mut cx, |this, cx| {
3582 let client = this.client.clone();
3583 this.buffer_store.update(cx, |this, cx| {
3584 this.handle_synchronize_buffers(envelope, cx, client)
3585 })
3586 })??;
3587
3588 Ok(response)
3589 }
3590
3591 async fn handle_search_candidate_buffers(
3592 this: Model<Self>,
3593 envelope: TypedEnvelope<proto::FindSearchCandidates>,
3594 mut cx: AsyncAppContext,
3595 ) -> Result<proto::FindSearchCandidatesResponse> {
3596 let peer_id = envelope.original_sender_id()?;
3597 let message = envelope.payload;
3598 let query = SearchQuery::from_proto(
3599 message
3600 .query
3601 .ok_or_else(|| anyhow!("missing query field"))?,
3602 )?;
3603 let mut results = this.update(&mut cx, |this, cx| {
3604 this.find_search_candidate_buffers(&query, message.limit as _, cx)
3605 })?;
3606
3607 let mut response = proto::FindSearchCandidatesResponse {
3608 buffer_ids: Vec::new(),
3609 };
3610
3611 while let Some(buffer) = results.next().await {
3612 this.update(&mut cx, |this, cx| {
3613 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
3614 response.buffer_ids.push(buffer_id.to_proto());
3615 })?;
3616 }
3617
3618 Ok(response)
3619 }
3620
3621 async fn handle_open_buffer_by_id(
3622 this: Model<Self>,
3623 envelope: TypedEnvelope<proto::OpenBufferById>,
3624 mut cx: AsyncAppContext,
3625 ) -> Result<proto::OpenBufferResponse> {
3626 let peer_id = envelope.original_sender_id()?;
3627 let buffer_id = BufferId::new(envelope.payload.id)?;
3628 let buffer = this
3629 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
3630 .await?;
3631 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3632 }
3633
3634 async fn handle_open_buffer_by_path(
3635 this: Model<Self>,
3636 envelope: TypedEnvelope<proto::OpenBufferByPath>,
3637 mut cx: AsyncAppContext,
3638 ) -> Result<proto::OpenBufferResponse> {
3639 let peer_id = envelope.original_sender_id()?;
3640 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3641 let open_buffer = this.update(&mut cx, |this, cx| {
3642 this.open_buffer(
3643 ProjectPath {
3644 worktree_id,
3645 path: PathBuf::from(envelope.payload.path).into(),
3646 },
3647 cx,
3648 )
3649 })?;
3650
3651 let buffer = open_buffer.await?;
3652 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3653 }
3654
3655 async fn handle_open_new_buffer(
3656 this: Model<Self>,
3657 envelope: TypedEnvelope<proto::OpenNewBuffer>,
3658 mut cx: AsyncAppContext,
3659 ) -> Result<proto::OpenBufferResponse> {
3660 let buffer = this
3661 .update(&mut cx, |this, cx| this.create_buffer(cx))?
3662 .await?;
3663 let peer_id = envelope.original_sender_id()?;
3664
3665 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
3666 }
3667
3668 fn respond_to_open_buffer_request(
3669 this: Model<Self>,
3670 buffer: Model<Buffer>,
3671 peer_id: proto::PeerId,
3672 cx: &mut AsyncAppContext,
3673 ) -> Result<proto::OpenBufferResponse> {
3674 this.update(cx, |this, cx| {
3675 let is_private = buffer
3676 .read(cx)
3677 .file()
3678 .map(|f| f.is_private())
3679 .unwrap_or_default();
3680 if is_private {
3681 Err(anyhow!(ErrorCode::UnsharedItem))
3682 } else {
3683 Ok(proto::OpenBufferResponse {
3684 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
3685 })
3686 }
3687 })?
3688 }
3689
3690 fn create_buffer_for_peer(
3691 &mut self,
3692 buffer: &Model<Buffer>,
3693 peer_id: proto::PeerId,
3694 cx: &mut AppContext,
3695 ) -> BufferId {
3696 self.buffer_store
3697 .update(cx, |buffer_store, cx| {
3698 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
3699 })
3700 .detach_and_log_err(cx);
3701 buffer.read(cx).remote_id()
3702 }
3703
3704 fn wait_for_remote_buffer(
3705 &mut self,
3706 id: BufferId,
3707 cx: &mut ModelContext<Self>,
3708 ) -> Task<Result<Model<Buffer>>> {
3709 self.buffer_store.update(cx, |buffer_store, cx| {
3710 buffer_store.wait_for_remote_buffer(id, cx)
3711 })
3712 }
3713
3714 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
3715 let project_id = match self.client_state {
3716 ProjectClientState::Remote {
3717 sharing_has_stopped,
3718 remote_id,
3719 ..
3720 } => {
3721 if sharing_has_stopped {
3722 return Task::ready(Err(anyhow!(
3723 "can't synchronize remote buffers on a readonly project"
3724 )));
3725 } else {
3726 remote_id
3727 }
3728 }
3729 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
3730 return Task::ready(Err(anyhow!(
3731 "can't synchronize remote buffers on a local project"
3732 )))
3733 }
3734 };
3735
3736 let client = self.client.clone();
3737 cx.spawn(move |this, mut cx| async move {
3738 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
3739 this.buffer_store.read(cx).buffer_version_info(cx)
3740 })?;
3741 let response = client
3742 .request(proto::SynchronizeBuffers {
3743 project_id,
3744 buffers,
3745 })
3746 .await?;
3747
3748 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
3749 response
3750 .buffers
3751 .into_iter()
3752 .map(|buffer| {
3753 let client = client.clone();
3754 let buffer_id = match BufferId::new(buffer.id) {
3755 Ok(id) => id,
3756 Err(e) => {
3757 return Task::ready(Err(e));
3758 }
3759 };
3760 let remote_version = language::proto::deserialize_version(&buffer.version);
3761 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
3762 let operations =
3763 buffer.read(cx).serialize_ops(Some(remote_version), cx);
3764 cx.background_executor().spawn(async move {
3765 let operations = operations.await;
3766 for chunk in split_operations(operations) {
3767 client
3768 .request(proto::UpdateBuffer {
3769 project_id,
3770 buffer_id: buffer_id.into(),
3771 operations: chunk,
3772 })
3773 .await?;
3774 }
3775 anyhow::Ok(())
3776 })
3777 } else {
3778 Task::ready(Ok(()))
3779 }
3780 })
3781 .collect::<Vec<_>>()
3782 })?;
3783
3784 // Any incomplete buffers have open requests waiting. Request that the host sends
3785 // creates these buffers for us again to unblock any waiting futures.
3786 for id in incomplete_buffer_ids {
3787 cx.background_executor()
3788 .spawn(client.request(proto::OpenBufferById {
3789 project_id,
3790 id: id.into(),
3791 }))
3792 .detach();
3793 }
3794
3795 futures::future::join_all(send_updates_for_buffers)
3796 .await
3797 .into_iter()
3798 .collect()
3799 })
3800 }
3801
3802 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
3803 self.worktree_store.read(cx).worktree_metadata_protos(cx)
3804 }
3805
3806 fn set_worktrees_from_proto(
3807 &mut self,
3808 worktrees: Vec<proto::WorktreeMetadata>,
3809 cx: &mut ModelContext<Project>,
3810 ) -> Result<()> {
3811 cx.notify();
3812 self.worktree_store.update(cx, |worktree_store, cx| {
3813 worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
3814 })
3815 }
3816
3817 fn set_collaborators_from_proto(
3818 &mut self,
3819 messages: Vec<proto::Collaborator>,
3820 cx: &mut ModelContext<Self>,
3821 ) -> Result<()> {
3822 let mut collaborators = HashMap::default();
3823 for message in messages {
3824 let collaborator = Collaborator::from_proto(message)?;
3825 collaborators.insert(collaborator.peer_id, collaborator);
3826 }
3827 for old_peer_id in self.collaborators.keys() {
3828 if !collaborators.contains_key(old_peer_id) {
3829 cx.emit(Event::CollaboratorLeft(*old_peer_id));
3830 }
3831 }
3832 self.collaborators = collaborators;
3833 Ok(())
3834 }
3835
3836 pub fn language_servers<'a>(
3837 &'a self,
3838 cx: &'a AppContext,
3839 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
3840 self.lsp_store.read(cx).language_servers()
3841 }
3842
3843 pub fn supplementary_language_servers<'a>(
3844 &'a self,
3845 cx: &'a AppContext,
3846 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
3847 self.lsp_store.read(cx).supplementary_language_servers()
3848 }
3849
3850 pub fn language_server_for_id(
3851 &self,
3852 id: LanguageServerId,
3853 cx: &AppContext,
3854 ) -> Option<Arc<LanguageServer>> {
3855 self.lsp_store.read(cx).language_server_for_id(id)
3856 }
3857
3858 pub fn language_servers_for_buffer<'a>(
3859 &'a self,
3860 buffer: &'a Buffer,
3861 cx: &'a AppContext,
3862 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
3863 self.lsp_store
3864 .read(cx)
3865 .language_servers_for_buffer(buffer, cx)
3866 }
3867
3868 pub fn language_server_for_buffer<'a>(
3869 &'a self,
3870 buffer: &'a Buffer,
3871 server_id: LanguageServerId,
3872 cx: &'a AppContext,
3873 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
3874 self.lsp_store
3875 .read(cx)
3876 .language_server_for_buffer(buffer, server_id, cx)
3877 }
3878}
3879
3880fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
3881 code_actions
3882 .iter()
3883 .flat_map(|(kind, enabled)| {
3884 if *enabled {
3885 Some(kind.clone().into())
3886 } else {
3887 None
3888 }
3889 })
3890 .collect()
3891}
3892
3893pub struct PathMatchCandidateSet {
3894 pub snapshot: Snapshot,
3895 pub include_ignored: bool,
3896 pub include_root_name: bool,
3897 pub candidates: Candidates,
3898}
3899
3900pub enum Candidates {
3901 /// Only consider directories.
3902 Directories,
3903 /// Only consider files.
3904 Files,
3905 /// Consider directories and files.
3906 Entries,
3907}
3908
3909impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
3910 type Candidates = PathMatchCandidateSetIter<'a>;
3911
3912 fn id(&self) -> usize {
3913 self.snapshot.id().to_usize()
3914 }
3915
3916 fn len(&self) -> usize {
3917 match self.candidates {
3918 Candidates::Files => {
3919 if self.include_ignored {
3920 self.snapshot.file_count()
3921 } else {
3922 self.snapshot.visible_file_count()
3923 }
3924 }
3925
3926 Candidates::Directories => {
3927 if self.include_ignored {
3928 self.snapshot.dir_count()
3929 } else {
3930 self.snapshot.visible_dir_count()
3931 }
3932 }
3933
3934 Candidates::Entries => {
3935 if self.include_ignored {
3936 self.snapshot.entry_count()
3937 } else {
3938 self.snapshot.visible_entry_count()
3939 }
3940 }
3941 }
3942 }
3943
3944 fn prefix(&self) -> Arc<str> {
3945 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
3946 self.snapshot.root_name().into()
3947 } else if self.include_root_name {
3948 format!("{}/", self.snapshot.root_name()).into()
3949 } else {
3950 Arc::default()
3951 }
3952 }
3953
3954 fn candidates(&'a self, start: usize) -> Self::Candidates {
3955 PathMatchCandidateSetIter {
3956 traversal: match self.candidates {
3957 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
3958 Candidates::Files => self.snapshot.files(self.include_ignored, start),
3959 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
3960 },
3961 }
3962 }
3963}
3964
3965pub struct PathMatchCandidateSetIter<'a> {
3966 traversal: Traversal<'a>,
3967}
3968
3969impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
3970 type Item = fuzzy::PathMatchCandidate<'a>;
3971
3972 fn next(&mut self) -> Option<Self::Item> {
3973 self.traversal
3974 .next()
3975 .map(|entry| fuzzy::PathMatchCandidate {
3976 is_dir: entry.kind.is_dir(),
3977 path: &entry.path,
3978 char_bag: entry.char_bag,
3979 })
3980 }
3981}
3982
3983impl EventEmitter<Event> for Project {}
3984
3985impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
3986 fn from(val: &'a ProjectPath) -> Self {
3987 SettingsLocation {
3988 worktree_id: val.worktree_id,
3989 path: val.path.as_ref(),
3990 }
3991 }
3992}
3993
3994impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
3995 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
3996 Self {
3997 worktree_id,
3998 path: path.as_ref().into(),
3999 }
4000 }
4001}
4002
4003pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4004 let mut path_components = path.components();
4005 let mut base_components = base.components();
4006 let mut components: Vec<Component> = Vec::new();
4007 loop {
4008 match (path_components.next(), base_components.next()) {
4009 (None, None) => break,
4010 (Some(a), None) => {
4011 components.push(a);
4012 components.extend(path_components.by_ref());
4013 break;
4014 }
4015 (None, _) => components.push(Component::ParentDir),
4016 (Some(a), Some(b)) if components.is_empty() && a == b => (),
4017 (Some(a), Some(Component::CurDir)) => components.push(a),
4018 (Some(a), Some(_)) => {
4019 components.push(Component::ParentDir);
4020 for _ in base_components {
4021 components.push(Component::ParentDir);
4022 }
4023 components.push(a);
4024 components.extend(path_components.by_ref());
4025 break;
4026 }
4027 }
4028 }
4029 components.iter().map(|c| c.as_os_str()).collect()
4030}
4031
4032fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4033 let mut result = base.to_path_buf();
4034 for component in path.components() {
4035 match component {
4036 Component::ParentDir => {
4037 result.pop();
4038 }
4039 Component::CurDir => (),
4040 _ => result.push(component),
4041 }
4042 }
4043 result
4044}
4045
4046/// ResolvedPath is a path that has been resolved to either a ProjectPath
4047/// or an AbsPath and that *exists*.
4048#[derive(Debug, Clone)]
4049pub enum ResolvedPath {
4050 ProjectPath(ProjectPath),
4051 AbsPath(PathBuf),
4052}
4053
4054impl ResolvedPath {
4055 pub fn abs_path(&self) -> Option<&Path> {
4056 match self {
4057 Self::AbsPath(path) => Some(path.as_path()),
4058 _ => None,
4059 }
4060 }
4061
4062 pub fn project_path(&self) -> Option<&ProjectPath> {
4063 match self {
4064 Self::ProjectPath(path) => Some(&path),
4065 _ => None,
4066 }
4067 }
4068}
4069
4070impl Item for Buffer {
4071 fn try_open(
4072 project: &Model<Project>,
4073 path: &ProjectPath,
4074 cx: &mut AppContext,
4075 ) -> Option<Task<Result<Model<Self>>>> {
4076 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4077 }
4078
4079 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
4080 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4081 }
4082
4083 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
4084 File::from_dyn(self.file()).map(|file| ProjectPath {
4085 worktree_id: file.worktree_id(cx),
4086 path: file.path().clone(),
4087 })
4088 }
4089}
4090
4091impl Completion {
4092 /// A key that can be used to sort completions when displaying
4093 /// them to the user.
4094 pub fn sort_key(&self) -> (usize, &str) {
4095 let kind_key = match self.lsp_completion.kind {
4096 Some(lsp::CompletionItemKind::KEYWORD) => 0,
4097 Some(lsp::CompletionItemKind::VARIABLE) => 1,
4098 _ => 2,
4099 };
4100 (kind_key, &self.label.text[self.label.filter_range.clone()])
4101 }
4102
4103 /// Whether this completion is a snippet.
4104 pub fn is_snippet(&self) -> bool {
4105 self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
4106 }
4107
4108 /// Returns the corresponding color for this completion.
4109 ///
4110 /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
4111 pub fn color(&self) -> Option<Hsla> {
4112 match self.lsp_completion.kind {
4113 Some(CompletionItemKind::COLOR) => color_extractor::extract_color(&self.lsp_completion),
4114 _ => None,
4115 }
4116 }
4117}
4118
4119#[derive(Debug)]
4120pub struct NoRepositoryError {}
4121
4122impl std::fmt::Display for NoRepositoryError {
4123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4124 write!(f, "no git repository for worktree found")
4125 }
4126}
4127
4128impl std::error::Error for NoRepositoryError {}
4129
4130pub fn sort_worktree_entries(entries: &mut [Entry]) {
4131 entries.sort_by(|entry_a, entry_b| {
4132 compare_paths(
4133 (&entry_a.path, entry_a.is_file()),
4134 (&entry_b.path, entry_b.is_file()),
4135 )
4136 });
4137}