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