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