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