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