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