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