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