1pub mod buffer_store;
2pub mod connection_manager;
3pub mod debounced_delay;
4pub mod lsp_command;
5pub mod lsp_ext_command;
6pub mod lsp_store;
7mod prettier_support;
8pub mod project_settings;
9pub mod search;
10mod task_inventory;
11pub mod terminals;
12pub mod worktree_store;
13
14#[cfg(test)]
15mod project_tests;
16
17mod environment;
18pub mod search_history;
19mod yarn;
20
21use anyhow::{anyhow, Context as _, Result};
22use buffer_store::{BufferStore, BufferStoreEvent};
23use client::{
24 proto, Client, Collaborator, DevServerProjectId, PendingEntitySubscription, ProjectId,
25 TypedEnvelope, UserStore,
26};
27use clock::ReplicaId;
28use collections::{BTreeSet, HashMap, HashSet};
29use debounced_delay::DebouncedDelay;
30pub use environment::ProjectEnvironment;
31use futures::{
32 channel::mpsc::{self, UnboundedReceiver},
33 future::try_join_all,
34 stream::FuturesUnordered,
35 AsyncWriteExt, FutureExt, StreamExt,
36};
37
38use git::{blame::Blame, repository::GitRepository};
39use gpui::{
40 AnyModel, AppContext, AsyncAppContext, BorrowAppContext, Context, EventEmitter, Model,
41 ModelContext, SharedString, Task, WeakModel, WindowContext,
42};
43use itertools::Itertools;
44use language::{
45 language_settings::{
46 language_settings, FormatOnSave, Formatter, InlayHintKind, LanguageSettings,
47 SelectedFormatter,
48 },
49 proto::{
50 deserialize_anchor, serialize_anchor, serialize_line_ending, serialize_version,
51 split_operations,
52 },
53 Buffer, BufferEvent, CachedLspAdapter, Capability, CodeLabel, ContextProvider, DiagnosticEntry,
54 Diff, Documentation, File as _, Language, LanguageRegistry, LanguageServerName, PointUtf16,
55 ToOffset, ToPointUtf16, Transaction, Unclipped,
56};
57use lsp::{CompletionContext, DocumentHighlightKind, LanguageServer, LanguageServerId};
58use lsp_command::*;
59use node_runtime::NodeRuntime;
60use parking_lot::{Mutex, RwLock};
61use paths::{local_tasks_file_relative_path, local_vscode_tasks_file_relative_path};
62use prettier_support::{DefaultPrettier, PrettierInstance};
63use project_settings::{LspSettings, ProjectSettings, SettingsObserver};
64use remote::SshSession;
65use rpc::{proto::SSH_PROJECT_ID, AnyProtoClient, ErrorCode};
66use search::{SearchInputKind, SearchQuery, SearchResult};
67use search_history::SearchHistory;
68use settings::{watch_config_file, Settings, SettingsLocation, SettingsStore};
69use smol::channel::Receiver;
70use snippet::Snippet;
71use snippet_provider::SnippetProvider;
72use std::{
73 borrow::Cow,
74 ops::Range,
75 path::{Component, Path, PathBuf},
76 str,
77 sync::Arc,
78 time::Duration,
79};
80use task::{
81 static_source::{StaticSource, TrackedFile},
82 HideStrategy, RevealStrategy, Shell, TaskContext, TaskTemplate, TaskVariables, VariableName,
83};
84use terminals::Terminals;
85use text::{Anchor, BufferId};
86use util::{defer, paths::compare_paths, ResultExt as _};
87use worktree::{CreatedEntry, Snapshot, Traversal};
88use worktree_store::{WorktreeStore, WorktreeStoreEvent};
89
90pub use fs::*;
91pub use language::Location;
92#[cfg(any(test, feature = "test-support"))]
93pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
94pub use task_inventory::{
95 BasicContextProvider, ContextProviderWithTasks, Inventory, TaskSourceKind,
96};
97pub use worktree::{
98 Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId, RepositoryEntry,
99 UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
100 FS_WATCH_LATENCY,
101};
102
103pub use buffer_store::ProjectTransaction;
104pub use lsp_store::{
105 DiagnosticSummary, LanguageServerLogType, LanguageServerProgress, LanguageServerPromptRequest,
106 LanguageServerStatus, LanguageServerToQuery, LspStore, LspStoreEvent,
107 SERVER_PROGRESS_THROTTLE_TIMEOUT,
108};
109
110const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
111const MAX_SEARCH_RESULT_FILES: usize = 5_000;
112const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
113
114pub trait Item {
115 fn try_open(
116 project: &Model<Project>,
117 path: &ProjectPath,
118 cx: &mut AppContext,
119 ) -> Option<Task<Result<Model<Self>>>>
120 where
121 Self: Sized;
122 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
123 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
124}
125
126#[derive(Clone)]
127pub enum OpenedBufferEvent {
128 Disconnected,
129 Ok(BufferId),
130 Err(BufferId, Arc<anyhow::Error>),
131}
132
133/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
134/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
135/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
136///
137/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
138pub struct Project {
139 active_entry: Option<ProjectEntryId>,
140 buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
141 languages: Arc<LanguageRegistry>,
142 client: Arc<client::Client>,
143 current_lsp_settings: HashMap<Arc<str>, LspSettings>,
144 join_project_response_message_id: u32,
145 user_store: Model<UserStore>,
146 fs: Arc<dyn Fs>,
147 ssh_session: Option<Arc<SshSession>>,
148 client_state: ProjectClientState,
149 collaborators: HashMap<proto::PeerId, Collaborator>,
150 client_subscriptions: Vec<client::Subscription>,
151 worktree_store: Model<WorktreeStore>,
152 buffer_store: Model<BufferStore>,
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_buffers: Arc<Mutex<RemotelyCreatedBuffers>>,
158 terminals: Terminals,
159 node: Option<Arc<dyn NodeRuntime>>,
160 default_prettier: DefaultPrettier,
161 prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
162 prettier_instances: HashMap<PathBuf, PrettierInstance>,
163 tasks: Model<Inventory>,
164 hosted_project_id: Option<ProjectId>,
165 dev_server_project_id: Option<client::DevServerProjectId>,
166 search_history: SearchHistory,
167 search_included_history: SearchHistory,
168 search_excluded_history: SearchHistory,
169 snippets: Model<SnippetProvider>,
170 last_formatting_failure: Option<String>,
171 buffers_being_formatted: HashSet<BufferId>,
172 environment: Model<ProjectEnvironment>,
173 settings_observer: Model<SettingsObserver>,
174}
175
176#[derive(Default)]
177struct RemotelyCreatedBuffers {
178 buffers: Vec<Model<Buffer>>,
179 retain_count: usize,
180}
181
182struct RemotelyCreatedBufferGuard {
183 remote_buffers: std::sync::Weak<Mutex<RemotelyCreatedBuffers>>,
184}
185
186impl Drop for RemotelyCreatedBufferGuard {
187 fn drop(&mut self) {
188 if let Some(remote_buffers) = self.remote_buffers.upgrade() {
189 let mut remote_buffers = remote_buffers.lock();
190 assert!(
191 remote_buffers.retain_count > 0,
192 "RemotelyCreatedBufferGuard dropped too many times"
193 );
194 remote_buffers.retain_count -= 1;
195 if remote_buffers.retain_count == 0 {
196 remote_buffers.buffers.clear();
197 }
198 }
199 }
200}
201/// Message ordered with respect to buffer operations
202#[derive(Debug)]
203enum BufferOrderedMessage {
204 Operation {
205 buffer_id: BufferId,
206 operation: proto::Operation,
207 },
208 LanguageServerUpdate {
209 language_server_id: LanguageServerId,
210 message: proto::update_language_server::Variant,
211 },
212 Resync,
213}
214
215#[derive(Debug)]
216enum ProjectClientState {
217 Local,
218 Shared {
219 remote_id: u64,
220 },
221 Remote {
222 sharing_has_stopped: bool,
223 capability: Capability,
224 remote_id: u64,
225 replica_id: ReplicaId,
226 in_room: bool,
227 },
228}
229
230#[derive(Clone, Debug, PartialEq)]
231pub enum Event {
232 LanguageServerAdded(LanguageServerId),
233 LanguageServerRemoved(LanguageServerId),
234 LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
235 Notification(String),
236 LanguageServerPrompt(LanguageServerPromptRequest),
237 LanguageNotFound(Model<Buffer>),
238 ActiveEntryChanged(Option<ProjectEntryId>),
239 ActivateProjectPanel,
240 WorktreeAdded,
241 WorktreeOrderChanged,
242 WorktreeRemoved(WorktreeId),
243 WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
244 WorktreeUpdatedGitRepositories,
245 DiskBasedDiagnosticsStarted {
246 language_server_id: LanguageServerId,
247 },
248 DiskBasedDiagnosticsFinished {
249 language_server_id: LanguageServerId,
250 },
251 DiagnosticsUpdated {
252 path: ProjectPath,
253 language_server_id: LanguageServerId,
254 },
255 RemoteIdChanged(Option<u64>),
256 DisconnectedFromHost,
257 Closed,
258 DeletedEntry(ProjectEntryId),
259 CollaboratorUpdated {
260 old_peer_id: proto::PeerId,
261 new_peer_id: proto::PeerId,
262 },
263 CollaboratorJoined(proto::PeerId),
264 CollaboratorLeft(proto::PeerId),
265 HostReshared,
266 Reshared,
267 Rejoined,
268 RefreshInlayHints,
269 RevealInProjectPanel(ProjectEntryId),
270 SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
271}
272
273#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
274pub struct ProjectPath {
275 pub worktree_id: WorktreeId,
276 pub path: Arc<Path>,
277}
278
279impl ProjectPath {
280 pub fn from_proto(p: proto::ProjectPath) -> Self {
281 Self {
282 worktree_id: WorktreeId::from_proto(p.worktree_id),
283 path: Arc::from(PathBuf::from(p.path)),
284 }
285 }
286
287 pub fn to_proto(&self) -> proto::ProjectPath {
288 proto::ProjectPath {
289 worktree_id: self.worktree_id.to_proto(),
290 path: self.path.to_string_lossy().to_string(),
291 }
292 }
293}
294
295#[derive(Debug, Clone, PartialEq, Eq)]
296pub struct InlayHint {
297 pub position: language::Anchor,
298 pub label: InlayHintLabel,
299 pub kind: Option<InlayHintKind>,
300 pub padding_left: bool,
301 pub padding_right: bool,
302 pub tooltip: Option<InlayHintTooltip>,
303 pub resolve_state: ResolveState,
304}
305
306/// The user's intent behind a given completion confirmation
307#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
308pub enum CompletionIntent {
309 /// The user intends to 'commit' this result, if possible
310 /// completion confirmations should run side effects
311 Complete,
312 /// The user intends to continue 'composing' this completion
313 /// completion confirmations should not run side effects and
314 /// let the user continue composing their action
315 Compose,
316}
317
318impl CompletionIntent {
319 pub fn is_complete(&self) -> bool {
320 self == &Self::Complete
321 }
322
323 pub fn is_compose(&self) -> bool {
324 self == &Self::Compose
325 }
326}
327
328/// A completion provided by a language server
329#[derive(Clone)]
330pub struct Completion {
331 /// The range of the buffer that will be replaced.
332 pub old_range: Range<Anchor>,
333 /// The new text that will be inserted.
334 pub new_text: String,
335 /// A label for this completion that is shown in the menu.
336 pub label: CodeLabel,
337 /// The id of the language server that produced this completion.
338 pub server_id: LanguageServerId,
339 /// The documentation for this completion.
340 pub documentation: Option<Documentation>,
341 /// The raw completion provided by the language server.
342 pub lsp_completion: lsp::CompletionItem,
343 /// An optional callback to invoke when this completion is confirmed.
344 /// Returns, whether new completions should be retriggered after the current one.
345 /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
346 /// if no confirmation is provided or `false` is returned, the completion will be committed.
347 pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut WindowContext) -> bool>>,
348}
349
350impl std::fmt::Debug for Completion {
351 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352 f.debug_struct("Completion")
353 .field("old_range", &self.old_range)
354 .field("new_text", &self.new_text)
355 .field("label", &self.label)
356 .field("server_id", &self.server_id)
357 .field("documentation", &self.documentation)
358 .field("lsp_completion", &self.lsp_completion)
359 .finish()
360 }
361}
362
363/// A completion provided by a language server
364#[derive(Clone, Debug)]
365pub(crate) struct CoreCompletion {
366 old_range: Range<Anchor>,
367 new_text: String,
368 server_id: LanguageServerId,
369 lsp_completion: lsp::CompletionItem,
370}
371
372/// A code action provided by a language server.
373#[derive(Clone, Debug)]
374pub struct CodeAction {
375 /// The id of the language server that produced this code action.
376 pub server_id: LanguageServerId,
377 /// The range of the buffer where this code action is applicable.
378 pub range: Range<Anchor>,
379 /// The raw code action provided by the language server.
380 pub lsp_action: lsp::CodeAction,
381}
382
383#[derive(Debug, Clone, PartialEq, Eq)]
384pub enum ResolveState {
385 Resolved,
386 CanResolve(LanguageServerId, Option<lsp::LSPAny>),
387 Resolving,
388}
389
390impl InlayHint {
391 pub fn text(&self) -> String {
392 match &self.label {
393 InlayHintLabel::String(s) => s.to_owned(),
394 InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
395 }
396 }
397}
398
399#[derive(Debug, Clone, PartialEq, Eq)]
400pub enum InlayHintLabel {
401 String(String),
402 LabelParts(Vec<InlayHintLabelPart>),
403}
404
405#[derive(Debug, Clone, PartialEq, Eq)]
406pub struct InlayHintLabelPart {
407 pub value: String,
408 pub tooltip: Option<InlayHintLabelPartTooltip>,
409 pub location: Option<(LanguageServerId, lsp::Location)>,
410}
411
412#[derive(Debug, Clone, PartialEq, Eq)]
413pub enum InlayHintTooltip {
414 String(String),
415 MarkupContent(MarkupContent),
416}
417
418#[derive(Debug, Clone, PartialEq, Eq)]
419pub enum InlayHintLabelPartTooltip {
420 String(String),
421 MarkupContent(MarkupContent),
422}
423
424#[derive(Debug, Clone, PartialEq, Eq)]
425pub struct MarkupContent {
426 pub kind: HoverBlockKind,
427 pub value: String,
428}
429
430#[derive(Debug, Clone)]
431pub struct LocationLink {
432 pub origin: Option<Location>,
433 pub target: Location,
434}
435
436#[derive(Debug)]
437pub struct DocumentHighlight {
438 pub range: Range<language::Anchor>,
439 pub kind: DocumentHighlightKind,
440}
441
442#[derive(Clone, Debug)]
443pub struct Symbol {
444 pub language_server_name: LanguageServerName,
445 pub source_worktree_id: WorktreeId,
446 pub path: ProjectPath,
447 pub label: CodeLabel,
448 pub name: String,
449 pub kind: lsp::SymbolKind,
450 pub range: Range<Unclipped<PointUtf16>>,
451 pub signature: [u8; 32],
452}
453
454#[derive(Clone, Debug, PartialEq)]
455pub struct HoverBlock {
456 pub text: String,
457 pub kind: HoverBlockKind,
458}
459
460#[derive(Clone, Debug, PartialEq, Eq)]
461pub enum HoverBlockKind {
462 PlainText,
463 Markdown,
464 Code { language: String },
465}
466
467#[derive(Debug, Clone)]
468pub struct Hover {
469 pub contents: Vec<HoverBlock>,
470 pub range: Option<Range<language::Anchor>>,
471 pub language: Option<Arc<Language>>,
472}
473
474impl Hover {
475 pub fn is_empty(&self) -> bool {
476 self.contents.iter().all(|block| block.text.is_empty())
477 }
478}
479
480#[derive(Debug, Clone, Copy, PartialEq, Eq)]
481pub enum FormatTrigger {
482 Save,
483 Manual,
484}
485
486// Currently, formatting operations are represented differently depending on
487// whether they come from a language server or an external command.
488#[derive(Debug)]
489enum FormatOperation {
490 Lsp(Vec<(Range<Anchor>, String)>),
491 External(Diff),
492 Prettier(Diff),
493}
494
495impl FormatTrigger {
496 fn from_proto(value: i32) -> FormatTrigger {
497 match value {
498 0 => FormatTrigger::Save,
499 1 => FormatTrigger::Manual,
500 _ => FormatTrigger::Save,
501 }
502 }
503}
504
505enum EntitySubscription {
506 Project(PendingEntitySubscription<Project>),
507 BufferStore(PendingEntitySubscription<BufferStore>),
508 WorktreeStore(PendingEntitySubscription<WorktreeStore>),
509 LspStore(PendingEntitySubscription<LspStore>),
510 SettingsObserver(PendingEntitySubscription<SettingsObserver>),
511}
512
513#[derive(Clone)]
514pub enum DirectoryLister {
515 Project(Model<Project>),
516 Local(Arc<dyn Fs>),
517}
518
519impl DirectoryLister {
520 pub fn is_local(&self, cx: &AppContext) -> bool {
521 match self {
522 DirectoryLister::Local(_) => true,
523 DirectoryLister::Project(project) => project.read(cx).is_local_or_ssh(),
524 }
525 }
526
527 pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &AppContext) -> Cow<'a, str> {
528 if self.is_local(cx) {
529 shellexpand::tilde(path)
530 } else {
531 Cow::from(path)
532 }
533 }
534
535 pub fn default_query(&self, cx: &mut AppContext) -> String {
536 if let DirectoryLister::Project(project) = self {
537 if let Some(worktree) = project.read(cx).visible_worktrees(cx).next() {
538 return worktree.read(cx).abs_path().to_string_lossy().to_string();
539 }
540 };
541 "~/".to_string()
542 }
543
544 pub fn list_directory(&self, path: String, cx: &mut AppContext) -> Task<Result<Vec<PathBuf>>> {
545 match self {
546 DirectoryLister::Project(project) => {
547 project.update(cx, |project, cx| project.list_directory(path, cx))
548 }
549 DirectoryLister::Local(fs) => {
550 let fs = fs.clone();
551 cx.background_executor().spawn(async move {
552 let mut results = vec![];
553 let expanded = shellexpand::tilde(&path);
554 let query = Path::new(expanded.as_ref());
555 let mut response = fs.read_dir(query).await?;
556 while let Some(path) = response.next().await {
557 if let Some(file_name) = path?.file_name() {
558 results.push(PathBuf::from(file_name.to_os_string()));
559 }
560 }
561 Ok(results)
562 })
563 }
564 }
565 }
566}
567
568#[cfg(any(test, feature = "test-support"))]
569pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
570 trigger_kind: lsp::CompletionTriggerKind::INVOKED,
571 trigger_character: None,
572};
573
574impl Project {
575 pub fn init_settings(cx: &mut AppContext) {
576 WorktreeSettings::register(cx);
577 ProjectSettings::register(cx);
578 }
579
580 pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
581 connection_manager::init(client.clone(), cx);
582 Self::init_settings(cx);
583
584 let client: AnyProtoClient = client.clone().into();
585 client.add_model_message_handler(Self::handle_add_collaborator);
586 client.add_model_message_handler(Self::handle_update_project_collaborator);
587 client.add_model_message_handler(Self::handle_remove_collaborator);
588 client.add_model_message_handler(Self::handle_update_project);
589 client.add_model_message_handler(Self::handle_unshare_project);
590 client.add_model_request_handler(Self::handle_update_buffer);
591 client.add_model_message_handler(Self::handle_update_worktree);
592 client.add_model_request_handler(Self::handle_reload_buffers);
593 client.add_model_request_handler(Self::handle_synchronize_buffers);
594 client.add_model_request_handler(Self::handle_format_buffers);
595 client.add_model_request_handler(Self::handle_search_project);
596 client.add_model_request_handler(Self::handle_search_candidate_buffers);
597 client.add_model_request_handler(Self::handle_open_buffer_by_id);
598 client.add_model_request_handler(Self::handle_open_buffer_by_path);
599 client.add_model_request_handler(Self::handle_open_new_buffer);
600 client.add_model_request_handler(Self::handle_task_context_for_location);
601 client.add_model_request_handler(Self::handle_task_templates);
602 client.add_model_message_handler(Self::handle_create_buffer_for_peer);
603
604 WorktreeStore::init(&client);
605 BufferStore::init(&client);
606 LspStore::init(&client);
607 SettingsObserver::init(&client);
608 }
609
610 pub fn local(
611 client: Arc<Client>,
612 node: Arc<dyn NodeRuntime>,
613 user_store: Model<UserStore>,
614 languages: Arc<LanguageRegistry>,
615 fs: Arc<dyn Fs>,
616 env: Option<HashMap<String, String>>,
617 cx: &mut AppContext,
618 ) -> Model<Self> {
619 cx.new_model(|cx: &mut ModelContext<Self>| {
620 let (tx, rx) = mpsc::unbounded();
621 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
622 .detach();
623 let tasks = Inventory::new(cx);
624 let global_snippets_dir = paths::config_dir().join("snippets");
625 let snippets =
626 SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
627
628 let worktree_store = cx.new_model(|_| WorktreeStore::new(false, fs.clone()));
629 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
630 .detach();
631
632 let buffer_store =
633 cx.new_model(|cx| BufferStore::new(worktree_store.clone(), None, cx));
634 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
635 .detach();
636
637 let settings_observer = cx.new_model(|cx| {
638 SettingsObserver::new_local(fs.clone(), worktree_store.clone(), cx)
639 });
640
641 let environment = ProjectEnvironment::new(&worktree_store, env, cx);
642 let lsp_store = cx.new_model(|cx| {
643 LspStore::new_local(
644 buffer_store.clone(),
645 worktree_store.clone(),
646 environment.clone(),
647 languages.clone(),
648 Some(client.http_client()),
649 fs.clone(),
650 cx,
651 )
652 });
653 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
654
655 Self {
656 buffer_ordered_messages_tx: tx,
657 collaborators: Default::default(),
658 worktree_store,
659 buffer_store,
660 lsp_store,
661 current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
662 join_project_response_message_id: 0,
663 client_state: ProjectClientState::Local,
664 client_subscriptions: Vec::new(),
665 _subscriptions: vec![
666 cx.observe_global::<SettingsStore>(Self::on_settings_changed),
667 cx.on_release(Self::release),
668 ],
669 active_entry: None,
670 snippets,
671 languages,
672 client,
673 user_store,
674 settings_observer,
675 fs,
676 ssh_session: None,
677 buffers_needing_diff: Default::default(),
678 git_diff_debouncer: DebouncedDelay::new(),
679 terminals: Terminals {
680 local_handles: Vec::new(),
681 },
682 node: Some(node),
683 default_prettier: DefaultPrettier::default(),
684 prettiers_per_worktree: HashMap::default(),
685 prettier_instances: HashMap::default(),
686 tasks,
687 hosted_project_id: None,
688 dev_server_project_id: None,
689 search_history: Self::new_search_history(),
690 environment,
691 remotely_created_buffers: Default::default(),
692 last_formatting_failure: None,
693 buffers_being_formatted: Default::default(),
694 search_included_history: Self::new_search_history(),
695 search_excluded_history: Self::new_search_history(),
696 }
697 })
698 }
699
700 pub fn ssh(
701 ssh: Arc<SshSession>,
702 client: Arc<Client>,
703 node: Arc<dyn NodeRuntime>,
704 user_store: Model<UserStore>,
705 languages: Arc<LanguageRegistry>,
706 fs: Arc<dyn Fs>,
707 cx: &mut AppContext,
708 ) -> Model<Self> {
709 cx.new_model(|cx: &mut ModelContext<Self>| {
710 let (tx, rx) = mpsc::unbounded();
711 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
712 .detach();
713 let tasks = Inventory::new(cx);
714 let global_snippets_dir = paths::config_dir().join("snippets");
715 let snippets =
716 SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
717
718 let worktree_store = cx.new_model(|_| {
719 let mut worktree_store = WorktreeStore::new(false, fs.clone());
720 worktree_store.set_upstream_client(ssh.clone().into());
721 worktree_store
722 });
723 cx.subscribe(&worktree_store, Self::on_worktree_store_event)
724 .detach();
725
726 let buffer_store =
727 cx.new_model(|cx| BufferStore::new(worktree_store.clone(), None, cx));
728 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
729 .detach();
730
731 let settings_observer = cx.new_model(|cx| {
732 SettingsObserver::new_ssh(ssh.clone().into(), worktree_store.clone(), cx)
733 });
734
735 let environment = ProjectEnvironment::new(&worktree_store, None, cx);
736 let lsp_store = cx.new_model(|cx| {
737 LspStore::new_ssh(
738 buffer_store.clone(),
739 worktree_store.clone(),
740 languages.clone(),
741 ssh.clone().into(),
742 0,
743 cx,
744 )
745 });
746 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
747
748 let this = Self {
749 buffer_ordered_messages_tx: tx,
750 collaborators: Default::default(),
751 worktree_store,
752 buffer_store,
753 lsp_store,
754 current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
755 join_project_response_message_id: 0,
756 client_state: ProjectClientState::Local,
757 client_subscriptions: Vec::new(),
758 _subscriptions: vec![
759 cx.observe_global::<SettingsStore>(Self::on_settings_changed),
760 cx.on_release(Self::release),
761 ],
762 active_entry: None,
763 snippets,
764 languages,
765 client,
766 user_store,
767 settings_observer,
768 fs,
769 ssh_session: Some(ssh.clone()),
770 buffers_needing_diff: Default::default(),
771 git_diff_debouncer: DebouncedDelay::new(),
772 terminals: Terminals {
773 local_handles: Vec::new(),
774 },
775 node: Some(node),
776 default_prettier: DefaultPrettier::default(),
777 prettiers_per_worktree: HashMap::default(),
778 prettier_instances: HashMap::default(),
779 tasks,
780 hosted_project_id: None,
781 dev_server_project_id: None,
782 search_history: Self::new_search_history(),
783 environment,
784 remotely_created_buffers: Default::default(),
785 last_formatting_failure: None,
786 buffers_being_formatted: Default::default(),
787 search_included_history: Self::new_search_history(),
788 search_excluded_history: Self::new_search_history(),
789 };
790
791 let client: AnyProtoClient = ssh.clone().into();
792
793 ssh.subscribe_to_entity(SSH_PROJECT_ID, &cx.handle());
794 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.buffer_store);
795 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.worktree_store);
796 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.lsp_store);
797 ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.settings_observer);
798 client.add_model_message_handler(Self::handle_update_worktree);
799 client.add_model_message_handler(Self::handle_create_buffer_for_peer);
800 client.add_model_message_handler(BufferStore::handle_update_buffer_file);
801 client.add_model_message_handler(BufferStore::handle_update_diff_base);
802 client.add_model_request_handler(BufferStore::handle_update_buffer);
803 LspStore::init(&client);
804 SettingsObserver::init(&client);
805
806 this
807 })
808 }
809
810 pub async fn remote(
811 remote_id: u64,
812 client: Arc<Client>,
813 user_store: Model<UserStore>,
814 languages: Arc<LanguageRegistry>,
815 fs: Arc<dyn Fs>,
816 cx: AsyncAppContext,
817 ) -> Result<Model<Self>> {
818 let project =
819 Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
820 cx.update(|cx| {
821 connection_manager::Manager::global(cx).update(cx, |manager, cx| {
822 manager.maintain_project_connection(&project, cx)
823 })
824 })?;
825 Ok(project)
826 }
827
828 pub async fn in_room(
829 remote_id: u64,
830 client: Arc<Client>,
831 user_store: Model<UserStore>,
832 languages: Arc<LanguageRegistry>,
833 fs: Arc<dyn Fs>,
834 cx: AsyncAppContext,
835 ) -> Result<Model<Self>> {
836 client.authenticate_and_connect(true, &cx).await?;
837
838 let subscriptions = [
839 EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
840 EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
841 EntitySubscription::WorktreeStore(
842 client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
843 ),
844 EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
845 EntitySubscription::SettingsObserver(
846 client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
847 ),
848 ];
849 let response = client
850 .request_envelope(proto::JoinProject {
851 project_id: remote_id,
852 })
853 .await?;
854 Self::from_join_project_response(
855 response,
856 subscriptions,
857 client,
858 user_store,
859 languages,
860 fs,
861 cx,
862 )
863 .await
864 }
865
866 async fn from_join_project_response(
867 response: TypedEnvelope<proto::JoinProjectResponse>,
868 subscriptions: [EntitySubscription; 5],
869 client: Arc<Client>,
870 user_store: Model<UserStore>,
871 languages: Arc<LanguageRegistry>,
872 fs: Arc<dyn Fs>,
873 mut cx: AsyncAppContext,
874 ) -> Result<Model<Self>> {
875 let remote_id = response.payload.project_id;
876 let role = response.payload.role();
877
878 let worktree_store = cx.new_model(|_| {
879 let mut store = WorktreeStore::new(true, fs.clone());
880 store.set_upstream_client(client.clone().into());
881 if let Some(dev_server_project_id) = response.payload.dev_server_project_id {
882 store.set_dev_server_project_id(DevServerProjectId(dev_server_project_id));
883 }
884 store
885 })?;
886 let buffer_store =
887 cx.new_model(|cx| BufferStore::new(worktree_store.clone(), Some(remote_id), cx))?;
888
889 let lsp_store = cx.new_model(|cx| {
890 let mut lsp_store = LspStore::new_remote(
891 buffer_store.clone(),
892 worktree_store.clone(),
893 languages.clone(),
894 client.clone().into(),
895 remote_id,
896 cx,
897 );
898 lsp_store.set_language_server_statuses_from_proto(response.payload.language_servers);
899 lsp_store
900 })?;
901
902 let settings_observer =
903 cx.new_model(|cx| SettingsObserver::new_remote(worktree_store.clone(), cx))?;
904
905 let this = cx.new_model(|cx| {
906 let replica_id = response.payload.replica_id as ReplicaId;
907 let tasks = Inventory::new(cx);
908 let global_snippets_dir = paths::config_dir().join("snippets");
909 let snippets =
910 SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
911
912 let mut worktrees = Vec::new();
913 for worktree in response.payload.worktrees {
914 let worktree =
915 Worktree::remote(remote_id, replica_id, worktree, client.clone().into(), cx);
916 worktrees.push(worktree);
917 }
918
919 let (tx, rx) = mpsc::unbounded();
920 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
921 .detach();
922
923 cx.subscribe(&buffer_store, Self::on_buffer_store_event)
924 .detach();
925 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
926
927 let mut this = Self {
928 buffer_ordered_messages_tx: tx,
929 buffer_store: buffer_store.clone(),
930 worktree_store: worktree_store.clone(),
931 lsp_store: lsp_store.clone(),
932 current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
933 active_entry: None,
934 collaborators: Default::default(),
935 join_project_response_message_id: response.message_id,
936 languages,
937 user_store: user_store.clone(),
938 snippets,
939 fs,
940 ssh_session: None,
941 settings_observer: settings_observer.clone(),
942 client_subscriptions: Default::default(),
943 _subscriptions: vec![cx.on_release(Self::release)],
944 client: client.clone(),
945 client_state: ProjectClientState::Remote {
946 sharing_has_stopped: false,
947 capability: Capability::ReadWrite,
948 remote_id,
949 replica_id,
950 in_room: response.payload.dev_server_project_id.is_none(),
951 },
952 buffers_needing_diff: Default::default(),
953 git_diff_debouncer: DebouncedDelay::new(),
954 terminals: Terminals {
955 local_handles: Vec::new(),
956 },
957 node: None,
958 default_prettier: DefaultPrettier::default(),
959 prettiers_per_worktree: HashMap::default(),
960 prettier_instances: HashMap::default(),
961 tasks,
962 hosted_project_id: None,
963 dev_server_project_id: response
964 .payload
965 .dev_server_project_id
966 .map(DevServerProjectId),
967 search_history: Self::new_search_history(),
968 search_included_history: Self::new_search_history(),
969 search_excluded_history: Self::new_search_history(),
970 environment: ProjectEnvironment::new(&worktree_store, None, cx),
971 remotely_created_buffers: Arc::new(Mutex::new(RemotelyCreatedBuffers::default())),
972 last_formatting_failure: None,
973 buffers_being_formatted: Default::default(),
974 };
975 this.set_role(role, cx);
976 for worktree in worktrees {
977 this.add_worktree(&worktree, cx);
978 }
979 this
980 })?;
981
982 let subscriptions = subscriptions
983 .into_iter()
984 .map(|s| match s {
985 EntitySubscription::BufferStore(subscription) => {
986 subscription.set_model(&buffer_store, &mut cx)
987 }
988 EntitySubscription::WorktreeStore(subscription) => {
989 subscription.set_model(&worktree_store, &mut cx)
990 }
991 EntitySubscription::SettingsObserver(subscription) => {
992 subscription.set_model(&settings_observer, &mut cx)
993 }
994 EntitySubscription::Project(subscription) => subscription.set_model(&this, &mut cx),
995 EntitySubscription::LspStore(subscription) => {
996 subscription.set_model(&lsp_store, &mut cx)
997 }
998 })
999 .collect::<Vec<_>>();
1000
1001 let user_ids = response
1002 .payload
1003 .collaborators
1004 .iter()
1005 .map(|peer| peer.user_id)
1006 .collect();
1007 user_store
1008 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
1009 .await?;
1010
1011 this.update(&mut cx, |this, cx| {
1012 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1013 this.client_subscriptions.extend(subscriptions);
1014 anyhow::Ok(())
1015 })??;
1016
1017 Ok(this)
1018 }
1019
1020 pub async fn hosted(
1021 remote_id: ProjectId,
1022 user_store: Model<UserStore>,
1023 client: Arc<Client>,
1024 languages: Arc<LanguageRegistry>,
1025 fs: Arc<dyn Fs>,
1026 cx: AsyncAppContext,
1027 ) -> Result<Model<Self>> {
1028 client.authenticate_and_connect(true, &cx).await?;
1029
1030 let subscriptions = [
1031 EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id.0)?),
1032 EntitySubscription::BufferStore(
1033 client.subscribe_to_entity::<BufferStore>(remote_id.0)?,
1034 ),
1035 EntitySubscription::WorktreeStore(
1036 client.subscribe_to_entity::<WorktreeStore>(remote_id.0)?,
1037 ),
1038 EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id.0)?),
1039 EntitySubscription::SettingsObserver(
1040 client.subscribe_to_entity::<SettingsObserver>(remote_id.0)?,
1041 ),
1042 ];
1043 let response = client
1044 .request_envelope(proto::JoinHostedProject {
1045 project_id: remote_id.0,
1046 })
1047 .await?;
1048 Self::from_join_project_response(
1049 response,
1050 subscriptions,
1051 client,
1052 user_store,
1053 languages,
1054 fs,
1055 cx,
1056 )
1057 .await
1058 }
1059
1060 fn new_search_history() -> SearchHistory {
1061 SearchHistory::new(
1062 Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1063 search_history::QueryInsertionBehavior::AlwaysInsert,
1064 )
1065 }
1066
1067 fn release(&mut self, cx: &mut AppContext) {
1068 match &self.client_state {
1069 ProjectClientState::Local => {}
1070 ProjectClientState::Shared { .. } => {
1071 let _ = self.unshare_internal(cx);
1072 }
1073 ProjectClientState::Remote { remote_id, .. } => {
1074 let _ = self.client.send(proto::LeaveProject {
1075 project_id: *remote_id,
1076 });
1077 self.disconnected_from_host_internal(cx);
1078 }
1079 }
1080 }
1081
1082 #[cfg(any(test, feature = "test-support"))]
1083 pub async fn example(
1084 root_paths: impl IntoIterator<Item = &Path>,
1085 cx: &mut AsyncAppContext,
1086 ) -> Model<Project> {
1087 use clock::FakeSystemClock;
1088
1089 let fs = Arc::new(RealFs::default());
1090 let languages = LanguageRegistry::test(cx.background_executor().clone());
1091 let clock = Arc::new(FakeSystemClock::default());
1092 let http_client = http_client::FakeHttpClient::with_404_response();
1093 let client = cx
1094 .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1095 .unwrap();
1096 let user_store = cx
1097 .new_model(|cx| UserStore::new(client.clone(), cx))
1098 .unwrap();
1099 let project = cx
1100 .update(|cx| {
1101 Project::local(
1102 client,
1103 node_runtime::FakeNodeRuntime::new(),
1104 user_store,
1105 Arc::new(languages),
1106 fs,
1107 None,
1108 cx,
1109 )
1110 })
1111 .unwrap();
1112 for path in root_paths {
1113 let (tree, _) = project
1114 .update(cx, |project, cx| {
1115 project.find_or_create_worktree(path, true, cx)
1116 })
1117 .unwrap()
1118 .await
1119 .unwrap();
1120 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1121 .unwrap()
1122 .await;
1123 }
1124 project
1125 }
1126
1127 #[cfg(any(test, feature = "test-support"))]
1128 pub async fn test(
1129 fs: Arc<dyn Fs>,
1130 root_paths: impl IntoIterator<Item = &Path>,
1131 cx: &mut gpui::TestAppContext,
1132 ) -> Model<Project> {
1133 use clock::FakeSystemClock;
1134
1135 let languages = LanguageRegistry::test(cx.executor());
1136 let clock = Arc::new(FakeSystemClock::default());
1137 let http_client = http_client::FakeHttpClient::with_404_response();
1138 let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1139 let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
1140 let project = cx.update(|cx| {
1141 Project::local(
1142 client,
1143 node_runtime::FakeNodeRuntime::new(),
1144 user_store,
1145 Arc::new(languages),
1146 fs,
1147 None,
1148 cx,
1149 )
1150 });
1151 for path in root_paths {
1152 let (tree, _) = project
1153 .update(cx, |project, cx| {
1154 project.find_or_create_worktree(path, true, cx)
1155 })
1156 .await
1157 .unwrap();
1158
1159 project.update(cx, |project, cx| {
1160 let tree_id = tree.read(cx).id();
1161 project.environment.update(cx, |environment, _| {
1162 environment.set_cached(&[(tree_id, HashMap::default())])
1163 });
1164 });
1165
1166 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1167 .await;
1168 }
1169 project
1170 }
1171
1172 pub fn lsp_store(&self) -> Model<LspStore> {
1173 self.lsp_store.clone()
1174 }
1175
1176 pub fn worktree_store(&self) -> Model<WorktreeStore> {
1177 self.worktree_store.clone()
1178 }
1179
1180 fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
1181 let mut language_servers_to_start = Vec::new();
1182 let mut language_formatters_to_check = Vec::new();
1183 for buffer in self.buffer_store.read(cx).buffers() {
1184 let buffer = buffer.read(cx);
1185 let buffer_file = File::from_dyn(buffer.file());
1186 let buffer_language = buffer.language();
1187 let settings = language_settings(buffer_language, buffer.file(), cx);
1188 if let Some(language) = buffer_language {
1189 if settings.enable_language_server {
1190 if let Some(file) = buffer_file {
1191 language_servers_to_start.push((file.worktree.clone(), language.name()));
1192 }
1193 }
1194 language_formatters_to_check
1195 .push((buffer_file.map(|f| f.worktree_id(cx)), settings.clone()));
1196 }
1197 }
1198
1199 let mut language_servers_to_stop = Vec::new();
1200 let mut language_servers_to_restart = Vec::new();
1201 let languages = self.languages.to_vec();
1202
1203 let new_lsp_settings = ProjectSettings::get_global(cx).lsp.clone();
1204 let current_lsp_settings = &self.current_lsp_settings;
1205 for (worktree_id, started_lsp_name) in self.lsp_store.read(cx).started_language_servers() {
1206 let language = languages.iter().find_map(|l| {
1207 let adapter = self
1208 .languages
1209 .lsp_adapters(&l.name())
1210 .iter()
1211 .find(|adapter| adapter.name == started_lsp_name)?
1212 .clone();
1213 Some((l, adapter))
1214 });
1215 if let Some((language, adapter)) = language {
1216 let worktree = self.worktree_for_id(worktree_id, cx);
1217 let file = worktree.as_ref().and_then(|tree| {
1218 tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
1219 });
1220 if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
1221 language_servers_to_stop.push((worktree_id, started_lsp_name.clone()));
1222 } else if let Some(worktree) = worktree {
1223 let server_name = &adapter.name.0;
1224 match (
1225 current_lsp_settings.get(server_name),
1226 new_lsp_settings.get(server_name),
1227 ) {
1228 (None, None) => {}
1229 (Some(_), None) | (None, Some(_)) => {
1230 language_servers_to_restart.push((worktree, language.name()));
1231 }
1232 (Some(current_lsp_settings), Some(new_lsp_settings)) => {
1233 if current_lsp_settings != new_lsp_settings {
1234 language_servers_to_restart.push((worktree, language.name()));
1235 }
1236 }
1237 }
1238 }
1239 }
1240 }
1241 self.current_lsp_settings = new_lsp_settings;
1242
1243 // Stop all newly-disabled language servers.
1244 self.lsp_store.update(cx, |lsp_store, cx| {
1245 for (worktree_id, adapter_name) in language_servers_to_stop {
1246 lsp_store
1247 .stop_language_server(worktree_id, adapter_name, cx)
1248 .detach();
1249 }
1250 });
1251
1252 let mut prettier_plugins_by_worktree = HashMap::default();
1253 for (worktree, language_settings) in language_formatters_to_check {
1254 if let Some(plugins) =
1255 prettier_support::prettier_plugins_for_language(&language_settings)
1256 {
1257 prettier_plugins_by_worktree
1258 .entry(worktree)
1259 .or_insert_with(HashSet::default)
1260 .extend(plugins.iter().cloned());
1261 }
1262 }
1263 for (worktree, prettier_plugins) in prettier_plugins_by_worktree {
1264 self.install_default_prettier(
1265 worktree,
1266 prettier_plugins.into_iter().map(Arc::from),
1267 cx,
1268 );
1269 }
1270
1271 // Start all the newly-enabled language servers.
1272 self.lsp_store.update(cx, |lsp_store, cx| {
1273 for (worktree, language) in language_servers_to_start {
1274 lsp_store.start_language_servers(&worktree, language, cx);
1275 }
1276
1277 // Restart all language servers with changed initialization options.
1278 for (worktree, language) in language_servers_to_restart {
1279 lsp_store.restart_language_servers(worktree, language, cx);
1280 }
1281 });
1282
1283 cx.notify();
1284 }
1285
1286 pub fn buffer_for_id(&self, remote_id: BufferId, cx: &AppContext) -> Option<Model<Buffer>> {
1287 self.buffer_store.read(cx).get(remote_id)
1288 }
1289
1290 pub fn languages(&self) -> &Arc<LanguageRegistry> {
1291 &self.languages
1292 }
1293
1294 pub fn client(&self) -> Arc<Client> {
1295 self.client.clone()
1296 }
1297
1298 pub fn user_store(&self) -> Model<UserStore> {
1299 self.user_store.clone()
1300 }
1301
1302 pub fn node_runtime(&self) -> Option<&Arc<dyn NodeRuntime>> {
1303 self.node.as_ref()
1304 }
1305
1306 pub fn opened_buffers(&self, cx: &AppContext) -> Vec<Model<Buffer>> {
1307 self.buffer_store.read(cx).buffers().collect()
1308 }
1309
1310 pub fn cli_environment(&self, cx: &AppContext) -> Option<HashMap<String, String>> {
1311 self.environment.read(cx).get_cli_environment()
1312 }
1313
1314 #[cfg(any(test, feature = "test-support"))]
1315 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
1316 self.buffer_store
1317 .read(cx)
1318 .get_by_path(&path.into(), cx)
1319 .is_some()
1320 }
1321
1322 pub fn fs(&self) -> &Arc<dyn Fs> {
1323 &self.fs
1324 }
1325
1326 pub fn remote_id(&self) -> Option<u64> {
1327 match self.client_state {
1328 ProjectClientState::Local => None,
1329 ProjectClientState::Shared { remote_id, .. }
1330 | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1331 }
1332 }
1333
1334 pub fn hosted_project_id(&self) -> Option<ProjectId> {
1335 self.hosted_project_id
1336 }
1337
1338 pub fn dev_server_project_id(&self) -> Option<DevServerProjectId> {
1339 self.dev_server_project_id
1340 }
1341
1342 pub fn supports_remote_terminal(&self, cx: &AppContext) -> bool {
1343 let Some(id) = self.dev_server_project_id else {
1344 return false;
1345 };
1346 let Some(server) = dev_server_projects::Store::global(cx)
1347 .read(cx)
1348 .dev_server_for_project(id)
1349 else {
1350 return false;
1351 };
1352 server.ssh_connection_string.is_some()
1353 }
1354
1355 pub fn ssh_connection_string(&self, cx: &ModelContext<Self>) -> Option<SharedString> {
1356 if self.is_local_or_ssh() {
1357 return None;
1358 }
1359
1360 let dev_server_id = self.dev_server_project_id()?;
1361 dev_server_projects::Store::global(cx)
1362 .read(cx)
1363 .dev_server_for_project(dev_server_id)?
1364 .ssh_connection_string
1365 .clone()
1366 }
1367
1368 pub fn replica_id(&self) -> ReplicaId {
1369 match self.client_state {
1370 ProjectClientState::Remote { replica_id, .. } => replica_id,
1371 _ => {
1372 if self.ssh_session.is_some() {
1373 1
1374 } else {
1375 0
1376 }
1377 }
1378 }
1379 }
1380
1381 fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
1382 cx.notify();
1383
1384 let ProjectClientState::Shared { remote_id } = self.client_state else {
1385 return;
1386 };
1387 let project_id = remote_id;
1388
1389 let update_project = self.client.request(proto::UpdateProject {
1390 project_id,
1391 worktrees: self.worktree_metadata_protos(cx),
1392 });
1393 cx.spawn(|this, mut cx| async move {
1394 update_project.await?;
1395 this.update(&mut cx, |this, cx| {
1396 let client = this.client.clone();
1397 let worktrees = this.worktree_store.read(cx).worktrees().collect::<Vec<_>>();
1398
1399 for worktree in worktrees {
1400 worktree.update(cx, |worktree, cx| {
1401 let client = client.clone();
1402 worktree.observe_updates(project_id, cx, {
1403 move |update| client.request(update).map(|result| result.is_ok())
1404 });
1405
1406 this.lsp_store.update(cx, |lsp_store, _| {
1407 lsp_store.send_diagnostic_summaries(worktree)
1408 })
1409 })?;
1410 }
1411
1412 anyhow::Ok(())
1413 })
1414 })
1415 .detach_and_log_err(cx);
1416 }
1417
1418 pub fn task_inventory(&self) -> &Model<Inventory> {
1419 &self.tasks
1420 }
1421
1422 pub fn snippets(&self) -> &Model<SnippetProvider> {
1423 &self.snippets
1424 }
1425
1426 pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1427 match kind {
1428 SearchInputKind::Query => &self.search_history,
1429 SearchInputKind::Include => &self.search_included_history,
1430 SearchInputKind::Exclude => &self.search_excluded_history,
1431 }
1432 }
1433
1434 pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1435 match kind {
1436 SearchInputKind::Query => &mut self.search_history,
1437 SearchInputKind::Include => &mut self.search_included_history,
1438 SearchInputKind::Exclude => &mut self.search_excluded_history,
1439 }
1440 }
1441
1442 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1443 &self.collaborators
1444 }
1445
1446 pub fn host(&self) -> Option<&Collaborator> {
1447 self.collaborators.values().find(|c| c.replica_id == 0)
1448 }
1449
1450 pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut AppContext) {
1451 self.worktree_store.update(cx, |store, _| {
1452 store.set_worktrees_reordered(worktrees_reordered);
1453 });
1454 }
1455
1456 /// Collect all worktrees, including ones that don't appear in the project panel
1457 pub fn worktrees<'a>(
1458 &self,
1459 cx: &'a AppContext,
1460 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1461 self.worktree_store.read(cx).worktrees()
1462 }
1463
1464 /// Collect all user-visible worktrees, the ones that appear in the project panel.
1465 pub fn visible_worktrees<'a>(
1466 &'a self,
1467 cx: &'a AppContext,
1468 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1469 self.worktree_store.read(cx).visible_worktrees(cx)
1470 }
1471
1472 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1473 self.visible_worktrees(cx)
1474 .map(|tree| tree.read(cx).root_name())
1475 }
1476
1477 pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
1478 self.worktree_store.read(cx).worktree_for_id(id, cx)
1479 }
1480
1481 pub fn worktree_for_entry(
1482 &self,
1483 entry_id: ProjectEntryId,
1484 cx: &AppContext,
1485 ) -> Option<Model<Worktree>> {
1486 self.worktree_store
1487 .read(cx)
1488 .worktree_for_entry(entry_id, cx)
1489 }
1490
1491 pub fn worktree_id_for_entry(
1492 &self,
1493 entry_id: ProjectEntryId,
1494 cx: &AppContext,
1495 ) -> Option<WorktreeId> {
1496 self.worktree_for_entry(entry_id, cx)
1497 .map(|worktree| worktree.read(cx).id())
1498 }
1499
1500 /// Checks if the entry is the root of a worktree.
1501 pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &AppContext) -> bool {
1502 self.worktree_for_entry(entry_id, cx)
1503 .map(|worktree| {
1504 worktree
1505 .read(cx)
1506 .root_entry()
1507 .is_some_and(|e| e.id == entry_id)
1508 })
1509 .unwrap_or(false)
1510 }
1511
1512 pub fn visibility_for_paths(&self, paths: &[PathBuf], cx: &AppContext) -> Option<bool> {
1513 paths
1514 .iter()
1515 .map(|path| self.visibility_for_path(path, cx))
1516 .max()
1517 .flatten()
1518 }
1519
1520 pub fn visibility_for_path(&self, path: &Path, cx: &AppContext) -> Option<bool> {
1521 self.worktrees(cx)
1522 .filter_map(|worktree| {
1523 let worktree = worktree.read(cx);
1524 worktree
1525 .as_local()?
1526 .contains_abs_path(path)
1527 .then(|| worktree.is_visible())
1528 })
1529 .max()
1530 }
1531
1532 pub fn create_entry(
1533 &mut self,
1534 project_path: impl Into<ProjectPath>,
1535 is_directory: bool,
1536 cx: &mut ModelContext<Self>,
1537 ) -> Task<Result<CreatedEntry>> {
1538 let project_path = project_path.into();
1539 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1540 return Task::ready(Err(anyhow!(format!(
1541 "No worktree for path {project_path:?}"
1542 ))));
1543 };
1544 worktree.update(cx, |worktree, cx| {
1545 worktree.create_entry(project_path.path, is_directory, cx)
1546 })
1547 }
1548
1549 pub fn copy_entry(
1550 &mut self,
1551 entry_id: ProjectEntryId,
1552 relative_worktree_source_path: Option<PathBuf>,
1553 new_path: impl Into<Arc<Path>>,
1554 cx: &mut ModelContext<Self>,
1555 ) -> Task<Result<Option<Entry>>> {
1556 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1557 return Task::ready(Ok(None));
1558 };
1559 worktree.update(cx, |worktree, cx| {
1560 worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1561 })
1562 }
1563
1564 pub fn rename_entry(
1565 &mut self,
1566 entry_id: ProjectEntryId,
1567 new_path: impl Into<Arc<Path>>,
1568 cx: &mut ModelContext<Self>,
1569 ) -> Task<Result<CreatedEntry>> {
1570 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1571 return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1572 };
1573 worktree.update(cx, |worktree, cx| {
1574 worktree.rename_entry(entry_id, new_path, cx)
1575 })
1576 }
1577
1578 pub fn delete_entry(
1579 &mut self,
1580 entry_id: ProjectEntryId,
1581 trash: bool,
1582 cx: &mut ModelContext<Self>,
1583 ) -> Option<Task<Result<()>>> {
1584 let worktree = self.worktree_for_entry(entry_id, cx)?;
1585 worktree.update(cx, |worktree, cx| {
1586 worktree.delete_entry(entry_id, trash, cx)
1587 })
1588 }
1589
1590 pub fn expand_entry(
1591 &mut self,
1592 worktree_id: WorktreeId,
1593 entry_id: ProjectEntryId,
1594 cx: &mut ModelContext<Self>,
1595 ) -> Option<Task<Result<()>>> {
1596 let worktree = self.worktree_for_id(worktree_id, cx)?;
1597 worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1598 }
1599
1600 pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1601 if !matches!(self.client_state, ProjectClientState::Local) {
1602 if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1603 if *in_room || self.dev_server_project_id.is_none() {
1604 return Err(anyhow!("project was already shared"));
1605 } else {
1606 *in_room = true;
1607 return Ok(());
1608 }
1609 } else {
1610 return Err(anyhow!("project was already shared"));
1611 }
1612 }
1613 self.client_subscriptions.extend([
1614 self.client
1615 .subscribe_to_entity(project_id)?
1616 .set_model(&cx.handle(), &mut cx.to_async()),
1617 self.client
1618 .subscribe_to_entity(project_id)?
1619 .set_model(&self.worktree_store, &mut cx.to_async()),
1620 self.client
1621 .subscribe_to_entity(project_id)?
1622 .set_model(&self.buffer_store, &mut cx.to_async()),
1623 self.client
1624 .subscribe_to_entity(project_id)?
1625 .set_model(&self.lsp_store, &mut cx.to_async()),
1626 self.client
1627 .subscribe_to_entity(project_id)?
1628 .set_model(&self.settings_observer, &mut cx.to_async()),
1629 ]);
1630
1631 self.buffer_store.update(cx, |buffer_store, cx| {
1632 buffer_store.shared(project_id, self.client.clone().into(), cx)
1633 });
1634 self.worktree_store.update(cx, |worktree_store, cx| {
1635 worktree_store.set_shared(true, cx);
1636 });
1637 self.lsp_store.update(cx, |lsp_store, cx| {
1638 lsp_store.shared(project_id, self.client.clone().into(), cx)
1639 });
1640 self.settings_observer.update(cx, |settings_observer, cx| {
1641 settings_observer.shared(project_id, self.client.clone().into(), cx)
1642 });
1643
1644 self.client_state = ProjectClientState::Shared {
1645 remote_id: project_id,
1646 };
1647
1648 self.metadata_changed(cx);
1649 cx.emit(Event::RemoteIdChanged(Some(project_id)));
1650 cx.notify();
1651 Ok(())
1652 }
1653
1654 pub fn reshared(
1655 &mut self,
1656 message: proto::ResharedProject,
1657 cx: &mut ModelContext<Self>,
1658 ) -> Result<()> {
1659 self.buffer_store
1660 .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
1661 self.set_collaborators_from_proto(message.collaborators, cx)?;
1662 self.metadata_changed(cx);
1663 cx.emit(Event::Reshared);
1664 Ok(())
1665 }
1666
1667 pub fn rejoined(
1668 &mut self,
1669 message: proto::RejoinedProject,
1670 message_id: u32,
1671 cx: &mut ModelContext<Self>,
1672 ) -> Result<()> {
1673 cx.update_global::<SettingsStore, _>(|store, cx| {
1674 self.worktree_store.update(cx, |worktree_store, cx| {
1675 for worktree in worktree_store.worktrees() {
1676 store
1677 .clear_local_settings(worktree.read(cx).id(), cx)
1678 .log_err();
1679 }
1680 });
1681 });
1682
1683 self.join_project_response_message_id = message_id;
1684 self.set_worktrees_from_proto(message.worktrees, cx)?;
1685 self.set_collaborators_from_proto(message.collaborators, cx)?;
1686 self.lsp_store.update(cx, |lsp_store, _| {
1687 lsp_store.set_language_server_statuses_from_proto(message.language_servers)
1688 });
1689 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
1690 .unwrap();
1691 cx.emit(Event::Rejoined);
1692 cx.notify();
1693 Ok(())
1694 }
1695
1696 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1697 self.unshare_internal(cx)?;
1698 self.metadata_changed(cx);
1699 cx.notify();
1700 Ok(())
1701 }
1702
1703 fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1704 if self.is_via_collab() {
1705 if self.dev_server_project_id().is_some() {
1706 if let ProjectClientState::Remote { in_room, .. } = &mut self.client_state {
1707 *in_room = false
1708 }
1709 return Ok(());
1710 } else {
1711 return Err(anyhow!("attempted to unshare a remote project"));
1712 }
1713 }
1714
1715 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
1716 self.client_state = ProjectClientState::Local;
1717 self.collaborators.clear();
1718 self.client_subscriptions.clear();
1719 self.worktree_store.update(cx, |store, cx| {
1720 store.set_shared(false, cx);
1721 });
1722 self.buffer_store.update(cx, |buffer_store, cx| {
1723 buffer_store.forget_shared_buffers();
1724 buffer_store.unshared(cx)
1725 });
1726 self.settings_observer.update(cx, |settings_observer, cx| {
1727 settings_observer.unshared(cx);
1728 });
1729 self.client
1730 .send(proto::UnshareProject {
1731 project_id: remote_id,
1732 })
1733 .ok();
1734 Ok(())
1735 } else {
1736 Err(anyhow!("attempted to unshare an unshared project"))
1737 }
1738 }
1739
1740 pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1741 if self.is_disconnected() {
1742 return;
1743 }
1744 self.disconnected_from_host_internal(cx);
1745 cx.emit(Event::DisconnectedFromHost);
1746 cx.notify();
1747 }
1748
1749 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut ModelContext<Self>) {
1750 let new_capability =
1751 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
1752 Capability::ReadWrite
1753 } else {
1754 Capability::ReadOnly
1755 };
1756 if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
1757 if *capability == new_capability {
1758 return;
1759 }
1760
1761 *capability = new_capability;
1762 for buffer in self.opened_buffers(cx) {
1763 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
1764 }
1765 }
1766 }
1767
1768 fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1769 if let ProjectClientState::Remote {
1770 sharing_has_stopped,
1771 ..
1772 } = &mut self.client_state
1773 {
1774 *sharing_has_stopped = true;
1775 self.collaborators.clear();
1776 self.worktree_store.update(cx, |store, cx| {
1777 store.disconnected_from_host(cx);
1778 });
1779 self.buffer_store.update(cx, |buffer_store, cx| {
1780 buffer_store.disconnected_from_host(cx)
1781 });
1782 self.lsp_store
1783 .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
1784 }
1785 }
1786
1787 pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1788 cx.emit(Event::Closed);
1789 }
1790
1791 pub fn is_disconnected(&self) -> bool {
1792 match &self.client_state {
1793 ProjectClientState::Remote {
1794 sharing_has_stopped,
1795 ..
1796 } => *sharing_has_stopped,
1797 _ => false,
1798 }
1799 }
1800
1801 pub fn capability(&self) -> Capability {
1802 match &self.client_state {
1803 ProjectClientState::Remote { capability, .. } => *capability,
1804 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
1805 }
1806 }
1807
1808 pub fn is_read_only(&self) -> bool {
1809 self.is_disconnected() || self.capability() == Capability::ReadOnly
1810 }
1811
1812 pub fn is_local(&self) -> bool {
1813 match &self.client_state {
1814 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1815 self.ssh_session.is_none()
1816 }
1817 ProjectClientState::Remote { .. } => false,
1818 }
1819 }
1820
1821 pub fn is_local_or_ssh(&self) -> bool {
1822 match &self.client_state {
1823 ProjectClientState::Local | ProjectClientState::Shared { .. } => true,
1824 ProjectClientState::Remote { .. } => false,
1825 }
1826 }
1827
1828 pub fn is_via_ssh(&self) -> bool {
1829 match &self.client_state {
1830 ProjectClientState::Local | ProjectClientState::Shared { .. } => {
1831 self.ssh_session.is_some()
1832 }
1833 ProjectClientState::Remote { .. } => false,
1834 }
1835 }
1836
1837 pub fn is_via_collab(&self) -> bool {
1838 match &self.client_state {
1839 ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
1840 ProjectClientState::Remote { .. } => true,
1841 }
1842 }
1843
1844 pub fn create_buffer(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<Model<Buffer>>> {
1845 self.buffer_store.update(cx, |buffer_store, cx| {
1846 buffer_store.create_buffer(
1847 if self.is_via_collab() {
1848 Some((self.client.clone().into(), self.remote_id().unwrap()))
1849 } else {
1850 None
1851 },
1852 cx,
1853 )
1854 })
1855 }
1856
1857 pub fn create_local_buffer(
1858 &mut self,
1859 text: &str,
1860 language: Option<Arc<Language>>,
1861 cx: &mut ModelContext<Self>,
1862 ) -> Model<Buffer> {
1863 if self.is_via_collab() {
1864 panic!("called create_local_buffer on a remote project")
1865 }
1866 self.buffer_store.update(cx, |buffer_store, cx| {
1867 buffer_store.create_local_buffer(text, language, cx)
1868 })
1869 }
1870
1871 pub fn open_path(
1872 &mut self,
1873 path: ProjectPath,
1874 cx: &mut ModelContext<Self>,
1875 ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
1876 let task = self.open_buffer(path.clone(), cx);
1877 cx.spawn(move |_, cx| async move {
1878 let buffer = task.await?;
1879 let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1880 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1881 })?;
1882
1883 let buffer: &AnyModel = &buffer;
1884 Ok((project_entry_id, buffer.clone()))
1885 })
1886 }
1887
1888 pub fn open_local_buffer(
1889 &mut self,
1890 abs_path: impl AsRef<Path>,
1891 cx: &mut ModelContext<Self>,
1892 ) -> Task<Result<Model<Buffer>>> {
1893 if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
1894 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1895 } else {
1896 Task::ready(Err(anyhow!("no such path")))
1897 }
1898 }
1899
1900 pub fn open_buffer(
1901 &mut self,
1902 path: impl Into<ProjectPath>,
1903 cx: &mut ModelContext<Self>,
1904 ) -> Task<Result<Model<Buffer>>> {
1905 if self.is_via_collab() && self.is_disconnected() {
1906 return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
1907 }
1908
1909 self.buffer_store.update(cx, |buffer_store, cx| {
1910 buffer_store.open_buffer(path.into(), cx)
1911 })
1912 }
1913
1914 pub fn open_buffer_by_id(
1915 &mut self,
1916 id: BufferId,
1917 cx: &mut ModelContext<Self>,
1918 ) -> Task<Result<Model<Buffer>>> {
1919 if let Some(buffer) = self.buffer_for_id(id, cx) {
1920 Task::ready(Ok(buffer))
1921 } else if self.is_local_or_ssh() {
1922 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1923 } else if let Some(project_id) = self.remote_id() {
1924 let request = self.client.request(proto::OpenBufferById {
1925 project_id,
1926 id: id.into(),
1927 });
1928 cx.spawn(move |this, mut cx| async move {
1929 let buffer_id = BufferId::new(request.await?.buffer_id)?;
1930 this.update(&mut cx, |this, cx| {
1931 this.wait_for_remote_buffer(buffer_id, cx)
1932 })?
1933 .await
1934 })
1935 } else {
1936 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1937 }
1938 }
1939
1940 pub fn save_buffers(
1941 &self,
1942 buffers: HashSet<Model<Buffer>>,
1943 cx: &mut ModelContext<Self>,
1944 ) -> Task<Result<()>> {
1945 cx.spawn(move |this, mut cx| async move {
1946 let save_tasks = buffers.into_iter().filter_map(|buffer| {
1947 this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
1948 .ok()
1949 });
1950 try_join_all(save_tasks).await?;
1951 Ok(())
1952 })
1953 }
1954
1955 pub fn save_buffer(
1956 &self,
1957 buffer: Model<Buffer>,
1958 cx: &mut ModelContext<Self>,
1959 ) -> Task<Result<()>> {
1960 self.buffer_store
1961 .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
1962 }
1963
1964 pub fn save_buffer_as(
1965 &mut self,
1966 buffer: Model<Buffer>,
1967 path: ProjectPath,
1968 cx: &mut ModelContext<Self>,
1969 ) -> Task<Result<()>> {
1970 self.buffer_store.update(cx, |buffer_store, cx| {
1971 buffer_store.save_buffer_as(buffer.clone(), path, cx)
1972 })
1973 }
1974
1975 pub fn get_open_buffer(
1976 &mut self,
1977 path: &ProjectPath,
1978 cx: &mut ModelContext<Self>,
1979 ) -> Option<Model<Buffer>> {
1980 self.buffer_store.read(cx).get_by_path(path, cx)
1981 }
1982
1983 fn register_buffer(
1984 &mut self,
1985 buffer: &Model<Buffer>,
1986 cx: &mut ModelContext<Self>,
1987 ) -> Result<()> {
1988 {
1989 let mut remotely_created_buffers = self.remotely_created_buffers.lock();
1990 if remotely_created_buffers.retain_count > 0 {
1991 remotely_created_buffers.buffers.push(buffer.clone())
1992 }
1993 }
1994
1995 self.request_buffer_diff_recalculation(buffer, cx);
1996
1997 cx.subscribe(buffer, |this, buffer, event, cx| {
1998 this.on_buffer_event(buffer, event, cx);
1999 })
2000 .detach();
2001
2002 Ok(())
2003 }
2004
2005 async fn send_buffer_ordered_messages(
2006 this: WeakModel<Self>,
2007 rx: UnboundedReceiver<BufferOrderedMessage>,
2008 mut cx: AsyncAppContext,
2009 ) -> Result<()> {
2010 const MAX_BATCH_SIZE: usize = 128;
2011
2012 let mut operations_by_buffer_id = HashMap::default();
2013 async fn flush_operations(
2014 this: &WeakModel<Project>,
2015 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2016 needs_resync_with_host: &mut bool,
2017 is_local: bool,
2018 cx: &mut AsyncAppContext,
2019 ) -> Result<()> {
2020 for (buffer_id, operations) in operations_by_buffer_id.drain() {
2021 let request = this.update(cx, |this, _| {
2022 let project_id = this.remote_id()?;
2023 Some(this.client.request(proto::UpdateBuffer {
2024 buffer_id: buffer_id.into(),
2025 project_id,
2026 operations,
2027 }))
2028 })?;
2029 if let Some(request) = request {
2030 if request.await.is_err() && !is_local {
2031 *needs_resync_with_host = true;
2032 break;
2033 }
2034 }
2035 }
2036 Ok(())
2037 }
2038
2039 let mut needs_resync_with_host = false;
2040 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2041
2042 while let Some(changes) = changes.next().await {
2043 let is_local = this.update(&mut cx, |this, _| this.is_local_or_ssh())?;
2044
2045 for change in changes {
2046 match change {
2047 BufferOrderedMessage::Operation {
2048 buffer_id,
2049 operation,
2050 } => {
2051 if needs_resync_with_host {
2052 continue;
2053 }
2054
2055 operations_by_buffer_id
2056 .entry(buffer_id)
2057 .or_insert(Vec::new())
2058 .push(operation);
2059 }
2060
2061 BufferOrderedMessage::Resync => {
2062 operations_by_buffer_id.clear();
2063 if this
2064 .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2065 .await
2066 .is_ok()
2067 {
2068 needs_resync_with_host = false;
2069 }
2070 }
2071
2072 BufferOrderedMessage::LanguageServerUpdate {
2073 language_server_id,
2074 message,
2075 } => {
2076 flush_operations(
2077 &this,
2078 &mut operations_by_buffer_id,
2079 &mut needs_resync_with_host,
2080 is_local,
2081 &mut cx,
2082 )
2083 .await?;
2084
2085 this.update(&mut cx, |this, _| {
2086 if let Some(project_id) = this.remote_id() {
2087 this.client
2088 .send(proto::UpdateLanguageServer {
2089 project_id,
2090 language_server_id: language_server_id.0 as u64,
2091 variant: Some(message),
2092 })
2093 .log_err();
2094 }
2095 })?;
2096 }
2097 }
2098 }
2099
2100 flush_operations(
2101 &this,
2102 &mut operations_by_buffer_id,
2103 &mut needs_resync_with_host,
2104 is_local,
2105 &mut cx,
2106 )
2107 .await?;
2108 }
2109
2110 Ok(())
2111 }
2112
2113 fn on_buffer_store_event(
2114 &mut self,
2115 _: Model<BufferStore>,
2116 event: &BufferStoreEvent,
2117 cx: &mut ModelContext<Self>,
2118 ) {
2119 match event {
2120 BufferStoreEvent::BufferAdded(buffer) => {
2121 self.register_buffer(buffer, cx).log_err();
2122 }
2123 BufferStoreEvent::BufferChangedFilePath { .. } => {}
2124 BufferStoreEvent::BufferDropped(buffer_id) => {
2125 if let Some(ref ssh_session) = self.ssh_session {
2126 ssh_session
2127 .send(proto::CloseBuffer {
2128 project_id: 0,
2129 buffer_id: buffer_id.to_proto(),
2130 })
2131 .log_err();
2132 }
2133 }
2134 }
2135 }
2136
2137 fn on_lsp_store_event(
2138 &mut self,
2139 _: Model<LspStore>,
2140 event: &LspStoreEvent,
2141 cx: &mut ModelContext<Self>,
2142 ) {
2143 match event {
2144 LspStoreEvent::DiagnosticsUpdated {
2145 language_server_id,
2146 path,
2147 } => cx.emit(Event::DiagnosticsUpdated {
2148 path: path.clone(),
2149 language_server_id: *language_server_id,
2150 }),
2151 LspStoreEvent::LanguageServerAdded(language_server_id) => {
2152 cx.emit(Event::LanguageServerAdded(*language_server_id))
2153 }
2154 LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2155 cx.emit(Event::LanguageServerAdded(*language_server_id))
2156 }
2157 LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2158 Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2159 ),
2160 LspStoreEvent::LanguageDetected {
2161 buffer,
2162 new_language,
2163 } => {
2164 let Some(new_language) = new_language else {
2165 cx.emit(Event::LanguageNotFound(buffer.clone()));
2166 return;
2167 };
2168 let buffer_file = buffer.read(cx).file().cloned();
2169 let settings =
2170 language_settings(Some(new_language), buffer_file.as_ref(), cx).clone();
2171 let buffer_file = File::from_dyn(buffer_file.as_ref());
2172 let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
2173 if let Some(prettier_plugins) =
2174 prettier_support::prettier_plugins_for_language(&settings)
2175 {
2176 self.install_default_prettier(
2177 worktree,
2178 prettier_plugins.iter().map(|s| Arc::from(s.as_str())),
2179 cx,
2180 );
2181 };
2182 }
2183 LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2184 LspStoreEvent::LanguageServerPrompt(prompt) => {
2185 cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2186 }
2187 LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2188 cx.emit(Event::DiskBasedDiagnosticsStarted {
2189 language_server_id: *language_server_id,
2190 });
2191 if self.is_local_or_ssh() {
2192 self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
2193 language_server_id: *language_server_id,
2194 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2195 Default::default(),
2196 ),
2197 })
2198 .ok();
2199 }
2200 }
2201 LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2202 cx.emit(Event::DiskBasedDiagnosticsFinished {
2203 language_server_id: *language_server_id,
2204 });
2205 if self.is_local_or_ssh() {
2206 self.enqueue_buffer_ordered_message(
2207 BufferOrderedMessage::LanguageServerUpdate {
2208 language_server_id: *language_server_id,
2209 message:
2210 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2211 Default::default(),
2212 ),
2213 },
2214 )
2215 .ok();
2216 }
2217 }
2218 LspStoreEvent::LanguageServerUpdate {
2219 language_server_id,
2220 message,
2221 } => {
2222 if self.is_local_or_ssh() {
2223 self.enqueue_buffer_ordered_message(
2224 BufferOrderedMessage::LanguageServerUpdate {
2225 language_server_id: *language_server_id,
2226 message: message.clone(),
2227 },
2228 )
2229 .ok();
2230 }
2231 }
2232 LspStoreEvent::Notification(message) => cx.emit(Event::Notification(message.clone())),
2233 LspStoreEvent::SnippetEdit {
2234 buffer_id,
2235 edits,
2236 most_recent_edit,
2237 } => {
2238 if most_recent_edit.replica_id == self.replica_id() {
2239 cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2240 }
2241 }
2242 LspStoreEvent::StartFormattingLocalBuffer(buffer_id) => {
2243 self.buffers_being_formatted.insert(*buffer_id);
2244 }
2245 LspStoreEvent::FinishFormattingLocalBuffer(buffer_id) => {
2246 self.buffers_being_formatted.remove(buffer_id);
2247 }
2248 }
2249 }
2250
2251 fn on_worktree_store_event(
2252 &mut self,
2253 _: Model<WorktreeStore>,
2254 event: &WorktreeStoreEvent,
2255 cx: &mut ModelContext<Self>,
2256 ) {
2257 match event {
2258 WorktreeStoreEvent::WorktreeAdded(worktree) => {
2259 self.on_worktree_added(worktree, cx);
2260 cx.emit(Event::WorktreeAdded);
2261 }
2262 WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2263 self.on_worktree_removed(*id, cx);
2264 cx.emit(Event::WorktreeRemoved(*id));
2265 }
2266 WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2267 }
2268 }
2269
2270 fn on_worktree_added(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
2271 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
2272 cx.subscribe(worktree, |this, worktree, event, cx| {
2273 let is_local = worktree.read(cx).is_local();
2274 match event {
2275 worktree::Event::UpdatedEntries(changes) => {
2276 if is_local {
2277 this.update_local_worktree_settings(&worktree, changes, cx);
2278 this.update_prettier_settings(&worktree, changes, cx);
2279 }
2280
2281 cx.emit(Event::WorktreeUpdatedEntries(
2282 worktree.read(cx).id(),
2283 changes.clone(),
2284 ));
2285
2286 let worktree_id = worktree.update(cx, |worktree, _| worktree.id());
2287 this.client()
2288 .telemetry()
2289 .report_discovered_project_events(worktree_id, changes);
2290 }
2291 worktree::Event::UpdatedGitRepositories(_) => {
2292 cx.emit(Event::WorktreeUpdatedGitRepositories);
2293 }
2294 worktree::Event::DeletedEntry(id) => cx.emit(Event::DeletedEntry(*id)),
2295 }
2296 })
2297 .detach();
2298 self.metadata_changed(cx);
2299 }
2300
2301 fn on_worktree_removed(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
2302 if let Some(dev_server_project_id) = self.dev_server_project_id {
2303 let paths: Vec<String> = self
2304 .visible_worktrees(cx)
2305 .filter_map(|worktree| {
2306 if worktree.read(cx).id() == id_to_remove {
2307 None
2308 } else {
2309 Some(worktree.read(cx).abs_path().to_string_lossy().to_string())
2310 }
2311 })
2312 .collect();
2313 if !paths.is_empty() {
2314 let request = self.client.request(proto::UpdateDevServerProject {
2315 dev_server_project_id: dev_server_project_id.0,
2316 paths,
2317 });
2318 cx.background_executor()
2319 .spawn(request)
2320 .detach_and_log_err(cx);
2321 }
2322 return;
2323 }
2324
2325 let mut prettier_instances_to_clean = FuturesUnordered::new();
2326 if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
2327 for path in prettier_paths.iter().flatten() {
2328 if let Some(prettier_instance) = self.prettier_instances.remove(path) {
2329 prettier_instances_to_clean.push(async move {
2330 prettier_instance
2331 .server()
2332 .await
2333 .map(|server| server.server_id())
2334 });
2335 }
2336 }
2337 }
2338 cx.spawn(|project, mut cx| async move {
2339 while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
2340 if let Some(prettier_server_id) = prettier_server_id {
2341 project
2342 .update(&mut cx, |project, cx| {
2343 project.lsp_store.update(cx, |lsp_store, cx| {
2344 lsp_store.unregister_supplementary_language_server(
2345 prettier_server_id,
2346 cx,
2347 );
2348 });
2349 })
2350 .ok();
2351 }
2352 }
2353 })
2354 .detach();
2355
2356 self.task_inventory().update(cx, |inventory, _| {
2357 inventory.remove_worktree_sources(id_to_remove);
2358 });
2359
2360 self.metadata_changed(cx);
2361 }
2362
2363 fn on_buffer_event(
2364 &mut self,
2365 buffer: Model<Buffer>,
2366 event: &BufferEvent,
2367 cx: &mut ModelContext<Self>,
2368 ) -> Option<()> {
2369 if matches!(
2370 event,
2371 BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2372 ) {
2373 self.request_buffer_diff_recalculation(&buffer, cx);
2374 }
2375
2376 let buffer_id = buffer.read(cx).remote_id();
2377 match event {
2378 BufferEvent::Operation(operation) => {
2379 let operation = language::proto::serialize_operation(operation);
2380
2381 if let Some(ssh) = &self.ssh_session {
2382 ssh.send(proto::UpdateBuffer {
2383 project_id: 0,
2384 buffer_id: buffer_id.to_proto(),
2385 operations: vec![operation.clone()],
2386 })
2387 .ok();
2388 }
2389
2390 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2391 buffer_id,
2392 operation,
2393 })
2394 .ok();
2395 }
2396
2397 BufferEvent::Reloaded => {
2398 if self.is_local_or_ssh() {
2399 if let Some(project_id) = self.remote_id() {
2400 let buffer = buffer.read(cx);
2401 self.client
2402 .send(proto::BufferReloaded {
2403 project_id,
2404 buffer_id: buffer.remote_id().to_proto(),
2405 version: serialize_version(&buffer.version()),
2406 mtime: buffer.saved_mtime().map(|t| t.into()),
2407 line_ending: serialize_line_ending(buffer.line_ending()) as i32,
2408 })
2409 .log_err();
2410 }
2411 }
2412 }
2413
2414 _ => {}
2415 }
2416
2417 None
2418 }
2419
2420 fn request_buffer_diff_recalculation(
2421 &mut self,
2422 buffer: &Model<Buffer>,
2423 cx: &mut ModelContext<Self>,
2424 ) {
2425 self.buffers_needing_diff.insert(buffer.downgrade());
2426 let first_insertion = self.buffers_needing_diff.len() == 1;
2427
2428 let settings = ProjectSettings::get_global(cx);
2429 let delay = if let Some(delay) = settings.git.gutter_debounce {
2430 delay
2431 } else {
2432 if first_insertion {
2433 let this = cx.weak_model();
2434 cx.defer(move |cx| {
2435 if let Some(this) = this.upgrade() {
2436 this.update(cx, |this, cx| {
2437 this.recalculate_buffer_diffs(cx).detach();
2438 });
2439 }
2440 });
2441 }
2442 return;
2443 };
2444
2445 const MIN_DELAY: u64 = 50;
2446 let delay = delay.max(MIN_DELAY);
2447 let duration = Duration::from_millis(delay);
2448
2449 self.git_diff_debouncer
2450 .fire_new(duration, cx, move |this, cx| {
2451 this.recalculate_buffer_diffs(cx)
2452 });
2453 }
2454
2455 fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2456 let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2457 cx.spawn(move |this, mut cx| async move {
2458 let tasks: Vec<_> = buffers
2459 .iter()
2460 .filter_map(|buffer| {
2461 let buffer = buffer.upgrade()?;
2462 buffer
2463 .update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx))
2464 .ok()
2465 .flatten()
2466 })
2467 .collect();
2468
2469 futures::future::join_all(tasks).await;
2470
2471 this.update(&mut cx, |this, cx| {
2472 if this.buffers_needing_diff.is_empty() {
2473 // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2474 for buffer in buffers {
2475 if let Some(buffer) = buffer.upgrade() {
2476 buffer.update(cx, |_, cx| cx.notify());
2477 }
2478 }
2479 } else {
2480 this.recalculate_buffer_diffs(cx).detach();
2481 }
2482 })
2483 .ok();
2484 })
2485 }
2486
2487 pub fn set_language_for_buffer(
2488 &mut self,
2489 buffer: &Model<Buffer>,
2490 new_language: Arc<Language>,
2491 cx: &mut ModelContext<Self>,
2492 ) {
2493 self.lsp_store.update(cx, |lsp_store, cx| {
2494 lsp_store.set_language_for_buffer(buffer, new_language, cx)
2495 })
2496 }
2497
2498 pub fn restart_language_servers_for_buffers(
2499 &mut self,
2500 buffers: impl IntoIterator<Item = Model<Buffer>>,
2501 cx: &mut ModelContext<Self>,
2502 ) {
2503 self.lsp_store.update(cx, |lsp_store, cx| {
2504 lsp_store.restart_language_servers_for_buffers(buffers, cx)
2505 })
2506 }
2507
2508 pub fn cancel_language_server_work_for_buffers(
2509 &mut self,
2510 buffers: impl IntoIterator<Item = Model<Buffer>>,
2511 cx: &mut ModelContext<Self>,
2512 ) {
2513 self.lsp_store.update(cx, |lsp_store, cx| {
2514 lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2515 })
2516 }
2517
2518 pub fn cancel_language_server_work(
2519 &mut self,
2520 server_id: LanguageServerId,
2521 token_to_cancel: Option<String>,
2522 cx: &mut ModelContext<Self>,
2523 ) {
2524 self.lsp_store.update(cx, |lsp_store, cx| {
2525 lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2526 })
2527 }
2528
2529 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
2530 self.buffer_ordered_messages_tx
2531 .unbounded_send(message)
2532 .map_err(|e| anyhow!(e))
2533 }
2534
2535 pub fn language_server_statuses<'a>(
2536 &'a self,
2537 cx: &'a AppContext,
2538 ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
2539 self.lsp_store.read(cx).language_server_statuses()
2540 }
2541
2542 pub fn last_formatting_failure(&self) -> Option<&str> {
2543 self.last_formatting_failure.as_deref()
2544 }
2545
2546 pub fn update_diagnostics(
2547 &mut self,
2548 language_server_id: LanguageServerId,
2549 params: lsp::PublishDiagnosticsParams,
2550 disk_based_sources: &[String],
2551 cx: &mut ModelContext<Self>,
2552 ) -> Result<()> {
2553 self.lsp_store.update(cx, |lsp_store, cx| {
2554 lsp_store.update_diagnostics(language_server_id, params, disk_based_sources, cx)
2555 })
2556 }
2557
2558 pub fn update_diagnostic_entries(
2559 &mut self,
2560 server_id: LanguageServerId,
2561 abs_path: PathBuf,
2562 version: Option<i32>,
2563 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2564 cx: &mut ModelContext<Project>,
2565 ) -> Result<(), anyhow::Error> {
2566 self.lsp_store.update(cx, |lsp_store, cx| {
2567 lsp_store.update_diagnostic_entries(server_id, abs_path, version, diagnostics, cx)
2568 })
2569 }
2570
2571 pub fn reload_buffers(
2572 &self,
2573 buffers: HashSet<Model<Buffer>>,
2574 push_to_history: bool,
2575 cx: &mut ModelContext<Self>,
2576 ) -> Task<Result<ProjectTransaction>> {
2577 let mut local_buffers = Vec::new();
2578 let mut remote_buffers = None;
2579 for buffer_handle in buffers {
2580 let buffer = buffer_handle.read(cx);
2581 if buffer.is_dirty() {
2582 if let Some(file) = File::from_dyn(buffer.file()) {
2583 if file.is_local() {
2584 local_buffers.push(buffer_handle);
2585 } else {
2586 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2587 }
2588 }
2589 }
2590 }
2591
2592 let remote_buffers = self.remote_id().zip(remote_buffers);
2593 let client = self.client.clone();
2594
2595 cx.spawn(move |this, mut cx| async move {
2596 let mut project_transaction = ProjectTransaction::default();
2597
2598 if let Some((project_id, remote_buffers)) = remote_buffers {
2599 let response = client
2600 .request(proto::ReloadBuffers {
2601 project_id,
2602 buffer_ids: remote_buffers
2603 .iter()
2604 .filter_map(|buffer| {
2605 buffer
2606 .update(&mut cx, |buffer, _| buffer.remote_id().into())
2607 .ok()
2608 })
2609 .collect(),
2610 })
2611 .await?
2612 .transaction
2613 .ok_or_else(|| anyhow!("missing transaction"))?;
2614 BufferStore::deserialize_project_transaction(
2615 this.read_with(&cx, |this, _| this.buffer_store.downgrade())?,
2616 response,
2617 push_to_history,
2618 cx.clone(),
2619 )
2620 .await?;
2621 }
2622
2623 for buffer in local_buffers {
2624 let transaction = buffer
2625 .update(&mut cx, |buffer, cx| buffer.reload(cx))?
2626 .await?;
2627 buffer.update(&mut cx, |buffer, cx| {
2628 if let Some(transaction) = transaction {
2629 if !push_to_history {
2630 buffer.forget_transaction(transaction.id);
2631 }
2632 project_transaction.0.insert(cx.handle(), transaction);
2633 }
2634 })?;
2635 }
2636
2637 Ok(project_transaction)
2638 })
2639 }
2640
2641 pub fn format(
2642 &mut self,
2643 buffers: HashSet<Model<Buffer>>,
2644 push_to_history: bool,
2645 trigger: FormatTrigger,
2646 cx: &mut ModelContext<Project>,
2647 ) -> Task<anyhow::Result<ProjectTransaction>> {
2648 if self.is_local_or_ssh() {
2649 let buffers_with_paths = buffers
2650 .into_iter()
2651 .map(|buffer_handle| {
2652 let buffer = buffer_handle.read(cx);
2653 let buffer_abs_path = File::from_dyn(buffer.file())
2654 .and_then(|file| file.as_local().map(|f| f.abs_path(cx)));
2655 (buffer_handle, buffer_abs_path)
2656 })
2657 .collect::<Vec<_>>();
2658
2659 cx.spawn(move |project, mut cx| async move {
2660 let result = Self::format_locally(
2661 project.clone(),
2662 buffers_with_paths,
2663 push_to_history,
2664 trigger,
2665 cx.clone(),
2666 )
2667 .await;
2668
2669 project.update(&mut cx, |project, _| match &result {
2670 Ok(_) => project.last_formatting_failure = None,
2671 Err(error) => {
2672 project.last_formatting_failure.replace(error.to_string());
2673 }
2674 })?;
2675
2676 result
2677 })
2678 } else {
2679 let remote_id = self.remote_id();
2680 let client = self.client.clone();
2681 cx.spawn(move |this, mut cx| async move {
2682 if let Some(project_id) = remote_id {
2683 let response = client
2684 .request(proto::FormatBuffers {
2685 project_id,
2686 trigger: trigger as i32,
2687 buffer_ids: buffers
2688 .iter()
2689 .map(|buffer| {
2690 buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
2691 })
2692 .collect::<Result<_>>()?,
2693 })
2694 .await?
2695 .transaction
2696 .ok_or_else(|| anyhow!("missing transaction"))?;
2697 BufferStore::deserialize_project_transaction(
2698 this.read_with(&cx, |this, _| this.buffer_store.downgrade())?,
2699 response,
2700 push_to_history,
2701 cx,
2702 )
2703 .await
2704 } else {
2705 Ok(ProjectTransaction::default())
2706 }
2707 })
2708 }
2709 }
2710
2711 async fn format_locally(
2712 project: WeakModel<Project>,
2713 mut buffers_with_paths: Vec<(Model<Buffer>, Option<PathBuf>)>,
2714 push_to_history: bool,
2715 trigger: FormatTrigger,
2716 mut cx: AsyncAppContext,
2717 ) -> anyhow::Result<ProjectTransaction> {
2718 // Do not allow multiple concurrent formatting requests for the
2719 // same buffer.
2720 let lsp_store = project.update(&mut cx, |this, cx| {
2721 buffers_with_paths.retain(|(buffer, _)| {
2722 this.buffers_being_formatted
2723 .insert(buffer.read(cx).remote_id())
2724 });
2725 this.lsp_store.downgrade()
2726 })?;
2727
2728 let _cleanup = defer({
2729 let this = project.clone();
2730 let mut cx = cx.clone();
2731 let buffers = &buffers_with_paths;
2732 move || {
2733 this.update(&mut cx, |this, cx| {
2734 for (buffer, _) in buffers {
2735 this.buffers_being_formatted
2736 .remove(&buffer.read(cx).remote_id());
2737 }
2738 })
2739 .ok();
2740 }
2741 });
2742
2743 let mut project_transaction = ProjectTransaction::default();
2744 for (buffer, buffer_abs_path) in &buffers_with_paths {
2745 let (primary_adapter_and_server, adapters_and_servers) =
2746 project.update(&mut cx, |project, cx| {
2747 let buffer = buffer.read(cx);
2748
2749 let adapters_and_servers = project
2750 .language_servers_for_buffer(buffer, cx)
2751 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
2752 .collect::<Vec<_>>();
2753
2754 let primary_adapter = project
2755 .lsp_store
2756 .read(cx)
2757 .primary_language_server_for_buffer(buffer, cx)
2758 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()));
2759
2760 (primary_adapter, adapters_and_servers)
2761 })?;
2762
2763 let settings = buffer.update(&mut cx, |buffer, cx| {
2764 language_settings(buffer.language(), buffer.file(), cx).clone()
2765 })?;
2766
2767 let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
2768 let ensure_final_newline = settings.ensure_final_newline_on_save;
2769
2770 // First, format buffer's whitespace according to the settings.
2771 let trailing_whitespace_diff = if remove_trailing_whitespace {
2772 Some(
2773 buffer
2774 .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
2775 .await,
2776 )
2777 } else {
2778 None
2779 };
2780 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
2781 buffer.finalize_last_transaction();
2782 buffer.start_transaction();
2783 if let Some(diff) = trailing_whitespace_diff {
2784 buffer.apply_diff(diff, cx);
2785 }
2786 if ensure_final_newline {
2787 buffer.ensure_final_newline(cx);
2788 }
2789 buffer.end_transaction(cx)
2790 })?;
2791
2792 // Apply the `code_actions_on_format` before we run the formatter.
2793 let code_actions = deserialize_code_actions(&settings.code_actions_on_format);
2794 #[allow(clippy::nonminimal_bool)]
2795 if !code_actions.is_empty()
2796 && !(trigger == FormatTrigger::Save && settings.format_on_save == FormatOnSave::Off)
2797 {
2798 LspStore::execute_code_actions_on_servers(
2799 &lsp_store,
2800 &adapters_and_servers,
2801 code_actions,
2802 buffer,
2803 push_to_history,
2804 &mut project_transaction,
2805 &mut cx,
2806 )
2807 .await?;
2808 }
2809
2810 // Apply language-specific formatting using either the primary language server
2811 // or external command.
2812 // Except for code actions, which are applied with all connected language servers.
2813 let primary_language_server =
2814 primary_adapter_and_server.map(|(_adapter, server)| server.clone());
2815 let server_and_buffer = primary_language_server
2816 .as_ref()
2817 .zip(buffer_abs_path.as_ref());
2818
2819 let prettier_settings = buffer.read_with(&cx, |buffer, cx| {
2820 language_settings(buffer.language(), buffer.file(), cx)
2821 .prettier
2822 .clone()
2823 })?;
2824
2825 let mut format_operations: Vec<FormatOperation> = vec![];
2826 {
2827 match trigger {
2828 FormatTrigger::Save => {
2829 match &settings.format_on_save {
2830 FormatOnSave::Off => {
2831 // nothing
2832 }
2833 FormatOnSave::On => {
2834 match &settings.formatter {
2835 SelectedFormatter::Auto => {
2836 // do the auto-format: prefer prettier, fallback to primary language server
2837 let diff = {
2838 if prettier_settings.allowed {
2839 Self::perform_format(
2840 &Formatter::Prettier,
2841 server_and_buffer,
2842 project.clone(),
2843 buffer,
2844 buffer_abs_path,
2845 &settings,
2846 &adapters_and_servers,
2847 push_to_history,
2848 &mut project_transaction,
2849 &mut cx,
2850 )
2851 .await
2852 } else {
2853 Self::perform_format(
2854 &Formatter::LanguageServer { name: None },
2855 server_and_buffer,
2856 project.clone(),
2857 buffer,
2858 buffer_abs_path,
2859 &settings,
2860 &adapters_and_servers,
2861 push_to_history,
2862 &mut project_transaction,
2863 &mut cx,
2864 )
2865 .await
2866 }
2867 }
2868 .log_err()
2869 .flatten();
2870 if let Some(op) = diff {
2871 format_operations.push(op);
2872 }
2873 }
2874 SelectedFormatter::List(formatters) => {
2875 for formatter in formatters.as_ref() {
2876 let diff = Self::perform_format(
2877 formatter,
2878 server_and_buffer,
2879 project.clone(),
2880 buffer,
2881 buffer_abs_path,
2882 &settings,
2883 &adapters_and_servers,
2884 push_to_history,
2885 &mut project_transaction,
2886 &mut cx,
2887 )
2888 .await
2889 .log_err()
2890 .flatten();
2891 if let Some(op) = diff {
2892 format_operations.push(op);
2893 }
2894
2895 // format with formatter
2896 }
2897 }
2898 }
2899 }
2900 FormatOnSave::List(formatters) => {
2901 for formatter in formatters.as_ref() {
2902 let diff = Self::perform_format(
2903 formatter,
2904 server_and_buffer,
2905 project.clone(),
2906 buffer,
2907 buffer_abs_path,
2908 &settings,
2909 &adapters_and_servers,
2910 push_to_history,
2911 &mut project_transaction,
2912 &mut cx,
2913 )
2914 .await
2915 .log_err()
2916 .flatten();
2917 if let Some(op) = diff {
2918 format_operations.push(op);
2919 }
2920 }
2921 }
2922 }
2923 }
2924 FormatTrigger::Manual => {
2925 match &settings.formatter {
2926 SelectedFormatter::Auto => {
2927 // do the auto-format: prefer prettier, fallback to primary language server
2928 let diff = {
2929 if prettier_settings.allowed {
2930 Self::perform_format(
2931 &Formatter::Prettier,
2932 server_and_buffer,
2933 project.clone(),
2934 buffer,
2935 buffer_abs_path,
2936 &settings,
2937 &adapters_and_servers,
2938 push_to_history,
2939 &mut project_transaction,
2940 &mut cx,
2941 )
2942 .await
2943 } else {
2944 Self::perform_format(
2945 &Formatter::LanguageServer { name: None },
2946 server_and_buffer,
2947 project.clone(),
2948 buffer,
2949 buffer_abs_path,
2950 &settings,
2951 &adapters_and_servers,
2952 push_to_history,
2953 &mut project_transaction,
2954 &mut cx,
2955 )
2956 .await
2957 }
2958 }
2959 .log_err()
2960 .flatten();
2961
2962 if let Some(op) = diff {
2963 format_operations.push(op)
2964 }
2965 }
2966 SelectedFormatter::List(formatters) => {
2967 for formatter in formatters.as_ref() {
2968 // format with formatter
2969 let diff = Self::perform_format(
2970 formatter,
2971 server_and_buffer,
2972 project.clone(),
2973 buffer,
2974 buffer_abs_path,
2975 &settings,
2976 &adapters_and_servers,
2977 push_to_history,
2978 &mut project_transaction,
2979 &mut cx,
2980 )
2981 .await
2982 .log_err()
2983 .flatten();
2984 if let Some(op) = diff {
2985 format_operations.push(op);
2986 }
2987 }
2988 }
2989 }
2990 }
2991 }
2992 }
2993
2994 buffer.update(&mut cx, |b, cx| {
2995 // If the buffer had its whitespace formatted and was edited while the language-specific
2996 // formatting was being computed, avoid applying the language-specific formatting, because
2997 // it can't be grouped with the whitespace formatting in the undo history.
2998 if let Some(transaction_id) = whitespace_transaction_id {
2999 if b.peek_undo_stack()
3000 .map_or(true, |e| e.transaction_id() != transaction_id)
3001 {
3002 format_operations.clear();
3003 }
3004 }
3005
3006 // Apply any language-specific formatting, and group the two formatting operations
3007 // in the buffer's undo history.
3008 for operation in format_operations {
3009 match operation {
3010 FormatOperation::Lsp(edits) => {
3011 b.edit(edits, None, cx);
3012 }
3013 FormatOperation::External(diff) => {
3014 b.apply_diff(diff, cx);
3015 }
3016 FormatOperation::Prettier(diff) => {
3017 b.apply_diff(diff, cx);
3018 }
3019 }
3020
3021 if let Some(transaction_id) = whitespace_transaction_id {
3022 b.group_until_transaction(transaction_id);
3023 } else if let Some(transaction) = project_transaction.0.get(buffer) {
3024 b.group_until_transaction(transaction.id)
3025 }
3026 }
3027
3028 if let Some(transaction) = b.finalize_last_transaction().cloned() {
3029 if !push_to_history {
3030 b.forget_transaction(transaction.id);
3031 }
3032 project_transaction.0.insert(buffer.clone(), transaction);
3033 }
3034 })?;
3035 }
3036
3037 Ok(project_transaction)
3038 }
3039
3040 #[allow(clippy::too_many_arguments)]
3041 async fn perform_format(
3042 formatter: &Formatter,
3043 primary_server_and_buffer: Option<(&Arc<LanguageServer>, &PathBuf)>,
3044 project: WeakModel<Project>,
3045 buffer: &Model<Buffer>,
3046 buffer_abs_path: &Option<PathBuf>,
3047 settings: &LanguageSettings,
3048 adapters_and_servers: &[(Arc<CachedLspAdapter>, Arc<LanguageServer>)],
3049 push_to_history: bool,
3050 transaction: &mut ProjectTransaction,
3051 cx: &mut AsyncAppContext,
3052 ) -> Result<Option<FormatOperation>, anyhow::Error> {
3053 let result = match formatter {
3054 Formatter::LanguageServer { name } => {
3055 if let Some((language_server, buffer_abs_path)) = primary_server_and_buffer {
3056 let language_server = if let Some(name) = name {
3057 adapters_and_servers
3058 .iter()
3059 .find_map(|(adapter, server)| {
3060 adapter.name.0.as_ref().eq(name.as_str()).then_some(server)
3061 })
3062 .unwrap_or(language_server)
3063 } else {
3064 language_server
3065 };
3066
3067 let lsp_store = project.update(cx, |p, _| p.lsp_store.downgrade())?;
3068 Some(FormatOperation::Lsp(
3069 LspStore::format_via_lsp(
3070 &lsp_store,
3071 buffer,
3072 buffer_abs_path,
3073 language_server,
3074 settings,
3075 cx,
3076 )
3077 .await
3078 .context("failed to format via language server")?,
3079 ))
3080 } else {
3081 None
3082 }
3083 }
3084 Formatter::Prettier => prettier_support::format_with_prettier(&project, buffer, cx)
3085 .await
3086 .transpose()
3087 .ok()
3088 .flatten(),
3089 Formatter::External { command, arguments } => {
3090 let buffer_abs_path = buffer_abs_path.as_ref().map(|path| path.as_path());
3091 Self::format_via_external_command(buffer, buffer_abs_path, command, arguments, cx)
3092 .await
3093 .context(format!(
3094 "failed to format via external command {:?}",
3095 command
3096 ))?
3097 .map(FormatOperation::External)
3098 }
3099 Formatter::CodeActions(code_actions) => {
3100 let code_actions = deserialize_code_actions(code_actions);
3101 let lsp_store = project.update(cx, |p, _| p.lsp_store.downgrade())?;
3102 if !code_actions.is_empty() {
3103 LspStore::execute_code_actions_on_servers(
3104 &lsp_store,
3105 adapters_and_servers,
3106 code_actions,
3107 buffer,
3108 push_to_history,
3109 transaction,
3110 cx,
3111 )
3112 .await?;
3113 }
3114 None
3115 }
3116 };
3117 anyhow::Ok(result)
3118 }
3119
3120 async fn format_via_external_command(
3121 buffer: &Model<Buffer>,
3122 buffer_abs_path: Option<&Path>,
3123 command: &str,
3124 arguments: &[String],
3125 cx: &mut AsyncAppContext,
3126 ) -> Result<Option<Diff>> {
3127 let working_dir_path = buffer.update(cx, |buffer, cx| {
3128 let file = File::from_dyn(buffer.file())?;
3129 let worktree = file.worktree.read(cx);
3130 let mut worktree_path = worktree.abs_path().to_path_buf();
3131 if worktree.root_entry()?.is_file() {
3132 worktree_path.pop();
3133 }
3134 Some(worktree_path)
3135 })?;
3136
3137 let mut child = smol::process::Command::new(command);
3138 #[cfg(target_os = "windows")]
3139 {
3140 use smol::process::windows::CommandExt;
3141 child.creation_flags(windows::Win32::System::Threading::CREATE_NO_WINDOW.0);
3142 }
3143
3144 if let Some(working_dir_path) = working_dir_path {
3145 child.current_dir(working_dir_path);
3146 }
3147
3148 let mut child = child
3149 .args(arguments.iter().map(|arg| {
3150 if let Some(buffer_abs_path) = buffer_abs_path {
3151 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3152 } else {
3153 arg.replace("{buffer_path}", "Untitled")
3154 }
3155 }))
3156 .stdin(smol::process::Stdio::piped())
3157 .stdout(smol::process::Stdio::piped())
3158 .stderr(smol::process::Stdio::piped())
3159 .spawn()?;
3160
3161 let stdin = child
3162 .stdin
3163 .as_mut()
3164 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3165 let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
3166 for chunk in text.chunks() {
3167 stdin.write_all(chunk.as_bytes()).await?;
3168 }
3169 stdin.flush().await?;
3170
3171 let output = child.output().await?;
3172 if !output.status.success() {
3173 return Err(anyhow!(
3174 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3175 output.status.code(),
3176 String::from_utf8_lossy(&output.stdout),
3177 String::from_utf8_lossy(&output.stderr),
3178 ));
3179 }
3180
3181 let stdout = String::from_utf8(output.stdout)?;
3182 Ok(Some(
3183 buffer
3184 .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
3185 .await,
3186 ))
3187 }
3188
3189 #[inline(never)]
3190 fn definition_impl(
3191 &self,
3192 buffer: &Model<Buffer>,
3193 position: PointUtf16,
3194 cx: &mut ModelContext<Self>,
3195 ) -> Task<Result<Vec<LocationLink>>> {
3196 self.request_lsp(
3197 buffer.clone(),
3198 LanguageServerToQuery::Primary,
3199 GetDefinition { position },
3200 cx,
3201 )
3202 }
3203 pub fn definition<T: ToPointUtf16>(
3204 &self,
3205 buffer: &Model<Buffer>,
3206 position: T,
3207 cx: &mut ModelContext<Self>,
3208 ) -> Task<Result<Vec<LocationLink>>> {
3209 let position = position.to_point_utf16(buffer.read(cx));
3210 self.definition_impl(buffer, position, cx)
3211 }
3212
3213 fn declaration_impl(
3214 &self,
3215 buffer: &Model<Buffer>,
3216 position: PointUtf16,
3217 cx: &mut ModelContext<Self>,
3218 ) -> Task<Result<Vec<LocationLink>>> {
3219 self.request_lsp(
3220 buffer.clone(),
3221 LanguageServerToQuery::Primary,
3222 GetDeclaration { position },
3223 cx,
3224 )
3225 }
3226
3227 pub fn declaration<T: ToPointUtf16>(
3228 &self,
3229 buffer: &Model<Buffer>,
3230 position: T,
3231 cx: &mut ModelContext<Self>,
3232 ) -> Task<Result<Vec<LocationLink>>> {
3233 let position = position.to_point_utf16(buffer.read(cx));
3234 self.declaration_impl(buffer, position, cx)
3235 }
3236
3237 fn type_definition_impl(
3238 &self,
3239 buffer: &Model<Buffer>,
3240 position: PointUtf16,
3241 cx: &mut ModelContext<Self>,
3242 ) -> Task<Result<Vec<LocationLink>>> {
3243 self.request_lsp(
3244 buffer.clone(),
3245 LanguageServerToQuery::Primary,
3246 GetTypeDefinition { position },
3247 cx,
3248 )
3249 }
3250
3251 pub fn type_definition<T: ToPointUtf16>(
3252 &self,
3253 buffer: &Model<Buffer>,
3254 position: T,
3255 cx: &mut ModelContext<Self>,
3256 ) -> Task<Result<Vec<LocationLink>>> {
3257 let position = position.to_point_utf16(buffer.read(cx));
3258 self.type_definition_impl(buffer, position, cx)
3259 }
3260
3261 pub fn implementation<T: ToPointUtf16>(
3262 &self,
3263 buffer: &Model<Buffer>,
3264 position: T,
3265 cx: &mut ModelContext<Self>,
3266 ) -> Task<Result<Vec<LocationLink>>> {
3267 let position = position.to_point_utf16(buffer.read(cx));
3268 self.request_lsp(
3269 buffer.clone(),
3270 LanguageServerToQuery::Primary,
3271 GetImplementation { position },
3272 cx,
3273 )
3274 }
3275
3276 pub fn references<T: ToPointUtf16>(
3277 &self,
3278 buffer: &Model<Buffer>,
3279 position: T,
3280 cx: &mut ModelContext<Self>,
3281 ) -> Task<Result<Vec<Location>>> {
3282 let position = position.to_point_utf16(buffer.read(cx));
3283 self.request_lsp(
3284 buffer.clone(),
3285 LanguageServerToQuery::Primary,
3286 GetReferences { position },
3287 cx,
3288 )
3289 }
3290
3291 fn document_highlights_impl(
3292 &self,
3293 buffer: &Model<Buffer>,
3294 position: PointUtf16,
3295 cx: &mut ModelContext<Self>,
3296 ) -> Task<Result<Vec<DocumentHighlight>>> {
3297 self.request_lsp(
3298 buffer.clone(),
3299 LanguageServerToQuery::Primary,
3300 GetDocumentHighlights { position },
3301 cx,
3302 )
3303 }
3304
3305 pub fn document_highlights<T: ToPointUtf16>(
3306 &self,
3307 buffer: &Model<Buffer>,
3308 position: T,
3309 cx: &mut ModelContext<Self>,
3310 ) -> Task<Result<Vec<DocumentHighlight>>> {
3311 let position = position.to_point_utf16(buffer.read(cx));
3312 self.document_highlights_impl(buffer, position, cx)
3313 }
3314
3315 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3316 self.lsp_store
3317 .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3318 }
3319
3320 pub fn open_buffer_for_symbol(
3321 &mut self,
3322 symbol: &Symbol,
3323 cx: &mut ModelContext<Self>,
3324 ) -> Task<Result<Model<Buffer>>> {
3325 self.lsp_store.update(cx, |lsp_store, cx| {
3326 lsp_store.open_buffer_for_symbol(symbol, cx)
3327 })
3328 }
3329
3330 pub fn open_local_buffer_via_lsp(
3331 &mut self,
3332 abs_path: lsp::Url,
3333 language_server_id: LanguageServerId,
3334 language_server_name: LanguageServerName,
3335 cx: &mut ModelContext<Self>,
3336 ) -> Task<Result<Model<Buffer>>> {
3337 self.lsp_store.update(cx, |lsp_store, cx| {
3338 lsp_store.open_local_buffer_via_lsp(
3339 abs_path,
3340 language_server_id,
3341 language_server_name,
3342 cx,
3343 )
3344 })
3345 }
3346
3347 pub fn signature_help<T: ToPointUtf16>(
3348 &self,
3349 buffer: &Model<Buffer>,
3350 position: T,
3351 cx: &mut ModelContext<Self>,
3352 ) -> Task<Vec<SignatureHelp>> {
3353 self.lsp_store.update(cx, |lsp_store, cx| {
3354 lsp_store.signature_help(buffer, position, cx)
3355 })
3356 }
3357
3358 pub fn hover<T: ToPointUtf16>(
3359 &self,
3360 buffer: &Model<Buffer>,
3361 position: T,
3362 cx: &mut ModelContext<Self>,
3363 ) -> Task<Vec<Hover>> {
3364 let position = position.to_point_utf16(buffer.read(cx));
3365 self.lsp_store
3366 .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3367 }
3368
3369 pub fn linked_edit(
3370 &self,
3371 buffer: &Model<Buffer>,
3372 position: Anchor,
3373 cx: &mut ModelContext<Self>,
3374 ) -> Task<Result<Vec<Range<Anchor>>>> {
3375 self.lsp_store.update(cx, |lsp_store, cx| {
3376 lsp_store.linked_edit(buffer, position, cx)
3377 })
3378 }
3379
3380 pub fn completions<T: ToOffset + ToPointUtf16>(
3381 &self,
3382 buffer: &Model<Buffer>,
3383 position: T,
3384 context: CompletionContext,
3385 cx: &mut ModelContext<Self>,
3386 ) -> Task<Result<Vec<Completion>>> {
3387 let position = position.to_point_utf16(buffer.read(cx));
3388 self.lsp_store.update(cx, |lsp_store, cx| {
3389 lsp_store.completions(buffer, position, context, cx)
3390 })
3391 }
3392
3393 pub fn resolve_completions(
3394 &self,
3395 buffer: Model<Buffer>,
3396 completion_indices: Vec<usize>,
3397 completions: Arc<RwLock<Box<[Completion]>>>,
3398 cx: &mut ModelContext<Self>,
3399 ) -> Task<Result<bool>> {
3400 self.lsp_store.update(cx, |lsp_store, cx| {
3401 lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
3402 })
3403 }
3404
3405 pub fn apply_additional_edits_for_completion(
3406 &self,
3407 buffer_handle: Model<Buffer>,
3408 completion: Completion,
3409 push_to_history: bool,
3410 cx: &mut ModelContext<Self>,
3411 ) -> Task<Result<Option<Transaction>>> {
3412 self.lsp_store.update(cx, |lsp_store, cx| {
3413 lsp_store.apply_additional_edits_for_completion(
3414 buffer_handle,
3415 completion,
3416 push_to_history,
3417 cx,
3418 )
3419 })
3420 }
3421
3422 pub fn code_actions<T: Clone + ToOffset>(
3423 &mut self,
3424 buffer_handle: &Model<Buffer>,
3425 range: Range<T>,
3426 cx: &mut ModelContext<Self>,
3427 ) -> Task<Vec<CodeAction>> {
3428 let buffer = buffer_handle.read(cx);
3429 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3430 self.lsp_store.update(cx, |lsp_store, cx| {
3431 lsp_store.code_actions(buffer_handle, range, cx)
3432 })
3433 }
3434
3435 pub fn apply_code_action(
3436 &self,
3437 buffer_handle: Model<Buffer>,
3438 action: CodeAction,
3439 push_to_history: bool,
3440 cx: &mut ModelContext<Self>,
3441 ) -> Task<Result<ProjectTransaction>> {
3442 self.lsp_store.update(cx, |lsp_store, cx| {
3443 lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3444 })
3445 }
3446
3447 fn prepare_rename_impl(
3448 &mut self,
3449 buffer: Model<Buffer>,
3450 position: PointUtf16,
3451 cx: &mut ModelContext<Self>,
3452 ) -> Task<Result<Option<Range<Anchor>>>> {
3453 self.request_lsp(
3454 buffer,
3455 LanguageServerToQuery::Primary,
3456 PrepareRename { position },
3457 cx,
3458 )
3459 }
3460 pub fn prepare_rename<T: ToPointUtf16>(
3461 &mut self,
3462 buffer: Model<Buffer>,
3463 position: T,
3464 cx: &mut ModelContext<Self>,
3465 ) -> Task<Result<Option<Range<Anchor>>>> {
3466 let position = position.to_point_utf16(buffer.read(cx));
3467 self.prepare_rename_impl(buffer, position, cx)
3468 }
3469
3470 fn perform_rename_impl(
3471 &mut self,
3472 buffer: Model<Buffer>,
3473 position: PointUtf16,
3474 new_name: String,
3475 push_to_history: bool,
3476 cx: &mut ModelContext<Self>,
3477 ) -> Task<Result<ProjectTransaction>> {
3478 let position = position.to_point_utf16(buffer.read(cx));
3479 self.request_lsp(
3480 buffer,
3481 LanguageServerToQuery::Primary,
3482 PerformRename {
3483 position,
3484 new_name,
3485 push_to_history,
3486 },
3487 cx,
3488 )
3489 }
3490 pub fn perform_rename<T: ToPointUtf16>(
3491 &mut self,
3492 buffer: Model<Buffer>,
3493 position: T,
3494 new_name: String,
3495 push_to_history: bool,
3496 cx: &mut ModelContext<Self>,
3497 ) -> Task<Result<ProjectTransaction>> {
3498 let position = position.to_point_utf16(buffer.read(cx));
3499 self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
3500 }
3501
3502 pub fn on_type_format<T: ToPointUtf16>(
3503 &mut self,
3504 buffer: Model<Buffer>,
3505 position: T,
3506 trigger: String,
3507 push_to_history: bool,
3508 cx: &mut ModelContext<Self>,
3509 ) -> Task<Result<Option<Transaction>>> {
3510 self.lsp_store.update(cx, |lsp_store, cx| {
3511 lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3512 })
3513 }
3514
3515 pub fn inlay_hints<T: ToOffset>(
3516 &mut self,
3517 buffer_handle: Model<Buffer>,
3518 range: Range<T>,
3519 cx: &mut ModelContext<Self>,
3520 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3521 let buffer = buffer_handle.read(cx);
3522 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3523 self.lsp_store.update(cx, |lsp_store, cx| {
3524 lsp_store.inlay_hints(buffer_handle, range, cx)
3525 })
3526 }
3527
3528 pub fn resolve_inlay_hint(
3529 &self,
3530 hint: InlayHint,
3531 buffer_handle: Model<Buffer>,
3532 server_id: LanguageServerId,
3533 cx: &mut ModelContext<Self>,
3534 ) -> Task<anyhow::Result<InlayHint>> {
3535 self.lsp_store.update(cx, |lsp_store, cx| {
3536 lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3537 })
3538 }
3539
3540 pub fn search(
3541 &mut self,
3542 query: SearchQuery,
3543 cx: &mut ModelContext<Self>,
3544 ) -> Receiver<SearchResult> {
3545 let (result_tx, result_rx) = smol::channel::unbounded();
3546
3547 let matching_buffers_rx = if query.is_opened_only() {
3548 self.sort_candidate_buffers(&query, cx)
3549 } else {
3550 self.search_for_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3551 };
3552
3553 cx.spawn(|_, cx| async move {
3554 let mut range_count = 0;
3555 let mut buffer_count = 0;
3556 let mut limit_reached = false;
3557 let query = Arc::new(query);
3558 let mut chunks = matching_buffers_rx.ready_chunks(64);
3559
3560 // Now that we know what paths match the query, we will load at most
3561 // 64 buffers at a time to avoid overwhelming the main thread. For each
3562 // opened buffer, we will spawn a background task that retrieves all the
3563 // ranges in the buffer matched by the query.
3564 'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3565 let mut chunk_results = Vec::new();
3566 for buffer in matching_buffer_chunk {
3567 let buffer = buffer.clone();
3568 let query = query.clone();
3569 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
3570 chunk_results.push(cx.background_executor().spawn(async move {
3571 let ranges = query
3572 .search(&snapshot, None)
3573 .await
3574 .iter()
3575 .map(|range| {
3576 snapshot.anchor_before(range.start)
3577 ..snapshot.anchor_after(range.end)
3578 })
3579 .collect::<Vec<_>>();
3580 anyhow::Ok((buffer, ranges))
3581 }));
3582 }
3583
3584 let chunk_results = futures::future::join_all(chunk_results).await;
3585 for result in chunk_results {
3586 if let Some((buffer, ranges)) = result.log_err() {
3587 range_count += ranges.len();
3588 buffer_count += 1;
3589 result_tx
3590 .send(SearchResult::Buffer { buffer, ranges })
3591 .await?;
3592 if buffer_count > MAX_SEARCH_RESULT_FILES
3593 || range_count > MAX_SEARCH_RESULT_RANGES
3594 {
3595 limit_reached = true;
3596 break 'outer;
3597 }
3598 }
3599 }
3600 }
3601
3602 if limit_reached {
3603 result_tx.send(SearchResult::LimitReached).await?;
3604 }
3605
3606 anyhow::Ok(())
3607 })
3608 .detach();
3609
3610 result_rx
3611 }
3612
3613 fn search_for_candidate_buffers(
3614 &mut self,
3615 query: &SearchQuery,
3616 limit: usize,
3617 cx: &mut ModelContext<Project>,
3618 ) -> Receiver<Model<Buffer>> {
3619 if self.is_local() {
3620 let fs = self.fs.clone();
3621 self.buffer_store.update(cx, |buffer_store, cx| {
3622 buffer_store.find_search_candidates(query, limit, fs, cx)
3623 })
3624 } else {
3625 self.search_for_candidate_buffers_remote(query, limit, cx)
3626 }
3627 }
3628
3629 fn sort_candidate_buffers(
3630 &mut self,
3631 search_query: &SearchQuery,
3632 cx: &mut ModelContext<Project>,
3633 ) -> Receiver<Model<Buffer>> {
3634 let worktree_store = self.worktree_store.read(cx);
3635 let mut buffers = search_query
3636 .buffers()
3637 .into_iter()
3638 .flatten()
3639 .filter(|buffer| {
3640 let b = buffer.read(cx);
3641 if let Some(file) = b.file() {
3642 if !search_query.file_matches(file.path()) {
3643 return false;
3644 }
3645 if let Some(entry) = b
3646 .entry_id(cx)
3647 .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3648 {
3649 if entry.is_ignored && !search_query.include_ignored() {
3650 return false;
3651 }
3652 }
3653 }
3654 true
3655 })
3656 .collect::<Vec<_>>();
3657 let (tx, rx) = smol::channel::unbounded();
3658 buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3659 (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3660 (None, Some(_)) => std::cmp::Ordering::Less,
3661 (Some(_), None) => std::cmp::Ordering::Greater,
3662 (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3663 });
3664 for buffer in buffers {
3665 tx.send_blocking(buffer.clone()).unwrap()
3666 }
3667
3668 rx
3669 }
3670
3671 fn search_for_candidate_buffers_remote(
3672 &mut self,
3673 query: &SearchQuery,
3674 limit: usize,
3675 cx: &mut ModelContext<Project>,
3676 ) -> Receiver<Model<Buffer>> {
3677 let (tx, rx) = smol::channel::unbounded();
3678
3679 let (client, remote_id): (AnyProtoClient, _) =
3680 if let Some(ssh_session) = self.ssh_session.clone() {
3681 (ssh_session.into(), 0)
3682 } else if let Some(remote_id) = self.remote_id() {
3683 (self.client.clone().into(), remote_id)
3684 } else {
3685 return rx;
3686 };
3687
3688 let request = client.request(proto::FindSearchCandidates {
3689 project_id: remote_id,
3690 query: Some(query.to_proto()),
3691 limit: limit as _,
3692 });
3693 let guard = self.retain_remotely_created_buffers(cx);
3694
3695 cx.spawn(move |this, mut cx| async move {
3696 let response = request.await?;
3697 for buffer_id in response.buffer_ids {
3698 let buffer_id = BufferId::new(buffer_id)?;
3699 let buffer = this
3700 .update(&mut cx, |this, cx| {
3701 this.wait_for_remote_buffer(buffer_id, cx)
3702 })?
3703 .await?;
3704 let _ = tx.send(buffer).await;
3705 }
3706
3707 drop(guard);
3708 anyhow::Ok(())
3709 })
3710 .detach_and_log_err(cx);
3711 rx
3712 }
3713
3714 pub fn request_lsp<R: LspCommand>(
3715 &self,
3716 buffer_handle: Model<Buffer>,
3717 server: LanguageServerToQuery,
3718 request: R,
3719 cx: &mut ModelContext<Self>,
3720 ) -> Task<Result<R::Response>>
3721 where
3722 <R::LspRequest as lsp::request::Request>::Result: Send,
3723 <R::LspRequest as lsp::request::Request>::Params: Send,
3724 {
3725 self.lsp_store.update(cx, |lsp_store, cx| {
3726 lsp_store.request_lsp(buffer_handle, server, request, cx)
3727 })
3728 }
3729
3730 /// Move a worktree to a new position in the worktree order.
3731 ///
3732 /// The worktree will moved to the opposite side of the destination worktree.
3733 ///
3734 /// # Example
3735 ///
3736 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3737 /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3738 ///
3739 /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3740 /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3741 ///
3742 /// # Errors
3743 ///
3744 /// An error will be returned if the worktree or destination worktree are not found.
3745 pub fn move_worktree(
3746 &mut self,
3747 source: WorktreeId,
3748 destination: WorktreeId,
3749 cx: &mut ModelContext<'_, Self>,
3750 ) -> Result<()> {
3751 self.worktree_store.update(cx, |worktree_store, cx| {
3752 worktree_store.move_worktree(source, destination, cx)
3753 })
3754 }
3755
3756 pub fn find_or_create_worktree(
3757 &mut self,
3758 abs_path: impl AsRef<Path>,
3759 visible: bool,
3760 cx: &mut ModelContext<Self>,
3761 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
3762 let abs_path = abs_path.as_ref();
3763 if let Some((tree, relative_path)) = self.find_worktree(abs_path, cx) {
3764 Task::ready(Ok((tree, relative_path)))
3765 } else {
3766 let worktree = self.create_worktree(abs_path, visible, cx);
3767 cx.background_executor()
3768 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
3769 }
3770 }
3771
3772 pub fn find_worktree(
3773 &self,
3774 abs_path: &Path,
3775 cx: &AppContext,
3776 ) -> Option<(Model<Worktree>, PathBuf)> {
3777 self.worktree_store.read_with(cx, |worktree_store, cx| {
3778 worktree_store.find_worktree(abs_path, cx)
3779 })
3780 }
3781
3782 pub fn is_shared(&self) -> bool {
3783 match &self.client_state {
3784 ProjectClientState::Shared { .. } => true,
3785 ProjectClientState::Local => false,
3786 ProjectClientState::Remote { in_room, .. } => *in_room,
3787 }
3788 }
3789
3790 // Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3791 pub fn resolve_existing_file_path(
3792 &self,
3793 path: &str,
3794 buffer: &Model<Buffer>,
3795 cx: &mut ModelContext<Self>,
3796 ) -> Task<Option<ResolvedPath>> {
3797 // TODO: ssh based remoting.
3798 if self.ssh_session.is_some() {
3799 return Task::ready(None);
3800 }
3801
3802 if self.is_local_or_ssh() {
3803 let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3804
3805 if expanded.is_absolute() {
3806 let fs = self.fs.clone();
3807 cx.background_executor().spawn(async move {
3808 let path = expanded.as_path();
3809 let exists = fs.is_file(path).await;
3810
3811 exists.then(|| ResolvedPath::AbsPath(expanded))
3812 })
3813 } else {
3814 self.resolve_path_in_worktrees(expanded, buffer, cx)
3815 }
3816 } else {
3817 let path = PathBuf::from(path);
3818 if path.is_absolute() || path.starts_with("~") {
3819 return Task::ready(None);
3820 }
3821
3822 self.resolve_path_in_worktrees(path, buffer, cx)
3823 }
3824 }
3825
3826 fn resolve_path_in_worktrees(
3827 &self,
3828 path: PathBuf,
3829 buffer: &Model<Buffer>,
3830 cx: &mut ModelContext<Self>,
3831 ) -> Task<Option<ResolvedPath>> {
3832 let mut candidates = vec![path.clone()];
3833
3834 if let Some(file) = buffer.read(cx).file() {
3835 if let Some(dir) = file.path().parent() {
3836 let joined = dir.to_path_buf().join(path);
3837 candidates.push(joined);
3838 }
3839 }
3840
3841 let worktrees = self.worktrees(cx).collect::<Vec<_>>();
3842 cx.spawn(|_, mut cx| async move {
3843 for worktree in worktrees {
3844 for candidate in candidates.iter() {
3845 let path = worktree
3846 .update(&mut cx, |worktree, _| {
3847 let root_entry_path = &worktree.root_entry()?.path;
3848
3849 let resolved = resolve_path(root_entry_path, candidate);
3850
3851 let stripped =
3852 resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3853
3854 worktree.entry_for_path(stripped).map(|entry| {
3855 ResolvedPath::ProjectPath(ProjectPath {
3856 worktree_id: worktree.id(),
3857 path: entry.path.clone(),
3858 })
3859 })
3860 })
3861 .ok()?;
3862
3863 if path.is_some() {
3864 return path;
3865 }
3866 }
3867 }
3868 None
3869 })
3870 }
3871
3872 pub fn list_directory(
3873 &self,
3874 query: String,
3875 cx: &mut ModelContext<Self>,
3876 ) -> Task<Result<Vec<PathBuf>>> {
3877 if self.is_local_or_ssh() {
3878 DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3879 } else if let Some(dev_server) = self.dev_server_project_id().and_then(|id| {
3880 dev_server_projects::Store::global(cx)
3881 .read(cx)
3882 .dev_server_for_project(id)
3883 }) {
3884 let request = proto::ListRemoteDirectory {
3885 dev_server_id: dev_server.id.0,
3886 path: query,
3887 };
3888 let response = self.client.request(request);
3889 cx.background_executor().spawn(async move {
3890 let response = response.await?;
3891 Ok(response.entries.into_iter().map(PathBuf::from).collect())
3892 })
3893 } else {
3894 Task::ready(Err(anyhow!("cannot list directory in remote project")))
3895 }
3896 }
3897
3898 fn create_worktree(
3899 &mut self,
3900 abs_path: impl AsRef<Path>,
3901 visible: bool,
3902 cx: &mut ModelContext<Self>,
3903 ) -> Task<Result<Model<Worktree>>> {
3904 self.worktree_store.update(cx, |worktree_store, cx| {
3905 worktree_store.create_worktree(abs_path, visible, cx)
3906 })
3907 }
3908
3909 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
3910 self.worktree_store.update(cx, |worktree_store, cx| {
3911 worktree_store.remove_worktree(id_to_remove, cx);
3912 });
3913 }
3914
3915 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
3916 self.worktree_store.update(cx, |worktree_store, cx| {
3917 worktree_store.add(worktree, cx);
3918 });
3919 }
3920
3921 fn update_local_worktree_settings(
3922 &mut self,
3923 worktree: &Model<Worktree>,
3924 changes: &UpdatedEntriesSet,
3925 cx: &mut ModelContext<Self>,
3926 ) {
3927 if worktree.read(cx).is_remote() {
3928 return;
3929 }
3930 let remote_worktree_id = worktree.read(cx).id();
3931
3932 for (path, _, change) in changes.iter() {
3933 let removed = change == &PathChange::Removed;
3934 let abs_path = match worktree.read(cx).absolutize(path) {
3935 Ok(abs_path) => abs_path,
3936 Err(e) => {
3937 log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
3938 continue;
3939 }
3940 };
3941
3942 if path.ends_with(local_tasks_file_relative_path()) {
3943 self.task_inventory().update(cx, |task_inventory, cx| {
3944 if removed {
3945 task_inventory.remove_local_static_source(&abs_path);
3946 } else {
3947 let fs = self.fs.clone();
3948 let task_abs_path = abs_path.clone();
3949 let tasks_file_rx =
3950 watch_config_file(cx.background_executor(), fs, task_abs_path);
3951 task_inventory.add_source(
3952 TaskSourceKind::Worktree {
3953 id: remote_worktree_id,
3954 abs_path,
3955 id_base: "local_tasks_for_worktree".into(),
3956 },
3957 |tx, cx| StaticSource::new(TrackedFile::new(tasks_file_rx, tx, cx)),
3958 cx,
3959 );
3960 }
3961 })
3962 } else if path.ends_with(local_vscode_tasks_file_relative_path()) {
3963 self.task_inventory().update(cx, |task_inventory, cx| {
3964 if removed {
3965 task_inventory.remove_local_static_source(&abs_path);
3966 } else {
3967 let fs = self.fs.clone();
3968 let task_abs_path = abs_path.clone();
3969 let tasks_file_rx =
3970 watch_config_file(cx.background_executor(), fs, task_abs_path);
3971 task_inventory.add_source(
3972 TaskSourceKind::Worktree {
3973 id: remote_worktree_id,
3974 abs_path,
3975 id_base: "local_vscode_tasks_for_worktree".into(),
3976 },
3977 |tx, cx| {
3978 StaticSource::new(TrackedFile::new_convertible::<
3979 task::VsCodeTaskFile,
3980 >(
3981 tasks_file_rx, tx, cx
3982 ))
3983 },
3984 cx,
3985 );
3986 }
3987 })
3988 }
3989 }
3990 }
3991
3992 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
3993 let new_active_entry = entry.and_then(|project_path| {
3994 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3995 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3996 Some(entry.id)
3997 });
3998 if new_active_entry != self.active_entry {
3999 self.active_entry = new_active_entry;
4000 self.lsp_store.update(cx, |lsp_store, _| {
4001 lsp_store.set_active_entry(new_active_entry);
4002 });
4003 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4004 }
4005 }
4006
4007 pub fn language_servers_running_disk_based_diagnostics<'a>(
4008 &'a self,
4009 cx: &'a AppContext,
4010 ) -> impl Iterator<Item = LanguageServerId> + 'a {
4011 self.lsp_store
4012 .read(cx)
4013 .language_servers_running_disk_based_diagnostics()
4014 }
4015
4016 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
4017 let mut summary = DiagnosticSummary::default();
4018 for (_, _, path_summary) in self.diagnostic_summaries(include_ignored, cx) {
4019 summary.error_count += path_summary.error_count;
4020 summary.warning_count += path_summary.warning_count;
4021 }
4022 summary
4023 }
4024
4025 pub fn diagnostic_summaries<'a>(
4026 &'a self,
4027 include_ignored: bool,
4028 cx: &'a AppContext,
4029 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4030 self.lsp_store
4031 .read(cx)
4032 .diagnostic_summaries(include_ignored, cx)
4033 }
4034
4035 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4036 self.active_entry
4037 }
4038
4039 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4040 self.worktree_store.read(cx).entry_for_path(path, cx)
4041 }
4042
4043 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4044 let worktree = self.worktree_for_entry(entry_id, cx)?;
4045 let worktree = worktree.read(cx);
4046 let worktree_id = worktree.id();
4047 let path = worktree.entry_for_id(entry_id)?.path.clone();
4048 Some(ProjectPath { worktree_id, path })
4049 }
4050
4051 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
4052 let workspace_root = self
4053 .worktree_for_id(project_path.worktree_id, cx)?
4054 .read(cx)
4055 .abs_path();
4056 let project_path = project_path.path.as_ref();
4057
4058 Some(if project_path == Path::new("") {
4059 workspace_root.to_path_buf()
4060 } else {
4061 workspace_root.join(project_path)
4062 })
4063 }
4064
4065 /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4066 /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4067 /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4068 /// the first visible worktree that has an entry for that relative path.
4069 ///
4070 /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4071 /// root name from paths.
4072 ///
4073 /// # Arguments
4074 ///
4075 /// * `path` - A full path that starts with a worktree root name, or alternatively a
4076 /// relative path within a visible worktree.
4077 /// * `cx` - A reference to the `AppContext`.
4078 ///
4079 /// # Returns
4080 ///
4081 /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4082 pub fn find_project_path(&self, path: &Path, cx: &AppContext) -> Option<ProjectPath> {
4083 let worktree_store = self.worktree_store.read(cx);
4084
4085 for worktree in worktree_store.visible_worktrees(cx) {
4086 let worktree_root_name = worktree.read(cx).root_name();
4087 if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
4088 return Some(ProjectPath {
4089 worktree_id: worktree.read(cx).id(),
4090 path: relative_path.into(),
4091 });
4092 }
4093 }
4094
4095 for worktree in worktree_store.visible_worktrees(cx) {
4096 let worktree = worktree.read(cx);
4097 if let Some(entry) = worktree.entry_for_path(path) {
4098 return Some(ProjectPath {
4099 worktree_id: worktree.id(),
4100 path: entry.path.clone(),
4101 });
4102 }
4103 }
4104
4105 None
4106 }
4107
4108 pub fn get_workspace_root(
4109 &self,
4110 project_path: &ProjectPath,
4111 cx: &AppContext,
4112 ) -> Option<PathBuf> {
4113 Some(
4114 self.worktree_for_id(project_path.worktree_id, cx)?
4115 .read(cx)
4116 .abs_path()
4117 .to_path_buf(),
4118 )
4119 }
4120
4121 pub fn get_repo(
4122 &self,
4123 project_path: &ProjectPath,
4124 cx: &AppContext,
4125 ) -> Option<Arc<dyn GitRepository>> {
4126 self.worktree_for_id(project_path.worktree_id, cx)?
4127 .read(cx)
4128 .as_local()?
4129 .local_git_repo(&project_path.path)
4130 }
4131
4132 pub fn get_first_worktree_root_repo(&self, cx: &AppContext) -> Option<Arc<dyn GitRepository>> {
4133 let worktree = self.visible_worktrees(cx).next()?.read(cx).as_local()?;
4134 let root_entry = worktree.root_git_entry()?;
4135 worktree.get_local_repo(&root_entry)?.repo().clone().into()
4136 }
4137
4138 pub fn blame_buffer(
4139 &self,
4140 buffer: &Model<Buffer>,
4141 version: Option<clock::Global>,
4142 cx: &AppContext,
4143 ) -> Task<Result<Blame>> {
4144 self.buffer_store.read(cx).blame_buffer(buffer, version, cx)
4145 }
4146
4147 // RPC message handlers
4148
4149 async fn handle_unshare_project(
4150 this: Model<Self>,
4151 _: TypedEnvelope<proto::UnshareProject>,
4152 mut cx: AsyncAppContext,
4153 ) -> Result<()> {
4154 this.update(&mut cx, |this, cx| {
4155 if this.is_local_or_ssh() {
4156 this.unshare(cx)?;
4157 } else {
4158 this.disconnected_from_host(cx);
4159 }
4160 Ok(())
4161 })?
4162 }
4163
4164 async fn handle_add_collaborator(
4165 this: Model<Self>,
4166 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4167 mut cx: AsyncAppContext,
4168 ) -> Result<()> {
4169 let collaborator = envelope
4170 .payload
4171 .collaborator
4172 .take()
4173 .ok_or_else(|| anyhow!("empty collaborator"))?;
4174
4175 let collaborator = Collaborator::from_proto(collaborator)?;
4176 this.update(&mut cx, |this, cx| {
4177 this.buffer_store.update(cx, |buffer_store, _| {
4178 buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4179 });
4180 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4181 this.collaborators
4182 .insert(collaborator.peer_id, collaborator);
4183 cx.notify();
4184 })?;
4185
4186 Ok(())
4187 }
4188
4189 async fn handle_update_project_collaborator(
4190 this: Model<Self>,
4191 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4192 mut cx: AsyncAppContext,
4193 ) -> Result<()> {
4194 let old_peer_id = envelope
4195 .payload
4196 .old_peer_id
4197 .ok_or_else(|| anyhow!("missing old peer id"))?;
4198 let new_peer_id = envelope
4199 .payload
4200 .new_peer_id
4201 .ok_or_else(|| anyhow!("missing new peer id"))?;
4202 this.update(&mut cx, |this, cx| {
4203 let collaborator = this
4204 .collaborators
4205 .remove(&old_peer_id)
4206 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4207 let is_host = collaborator.replica_id == 0;
4208 this.collaborators.insert(new_peer_id, collaborator);
4209
4210 log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4211 this.buffer_store.update(cx, |buffer_store, _| {
4212 buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4213 });
4214
4215 if is_host {
4216 this.buffer_store
4217 .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4218 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4219 .unwrap();
4220 cx.emit(Event::HostReshared);
4221 }
4222
4223 cx.emit(Event::CollaboratorUpdated {
4224 old_peer_id,
4225 new_peer_id,
4226 });
4227 cx.notify();
4228 Ok(())
4229 })?
4230 }
4231
4232 async fn handle_remove_collaborator(
4233 this: Model<Self>,
4234 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4235 mut cx: AsyncAppContext,
4236 ) -> Result<()> {
4237 this.update(&mut cx, |this, cx| {
4238 let peer_id = envelope
4239 .payload
4240 .peer_id
4241 .ok_or_else(|| anyhow!("invalid peer id"))?;
4242 let replica_id = this
4243 .collaborators
4244 .remove(&peer_id)
4245 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4246 .replica_id;
4247 this.buffer_store.update(cx, |buffer_store, cx| {
4248 buffer_store.forget_shared_buffers_for(&peer_id);
4249 for buffer in buffer_store.buffers() {
4250 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4251 }
4252 });
4253
4254 cx.emit(Event::CollaboratorLeft(peer_id));
4255 cx.notify();
4256 Ok(())
4257 })?
4258 }
4259
4260 async fn handle_update_project(
4261 this: Model<Self>,
4262 envelope: TypedEnvelope<proto::UpdateProject>,
4263 mut cx: AsyncAppContext,
4264 ) -> Result<()> {
4265 this.update(&mut cx, |this, cx| {
4266 // Don't handle messages that were sent before the response to us joining the project
4267 if envelope.message_id > this.join_project_response_message_id {
4268 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4269 }
4270 Ok(())
4271 })?
4272 }
4273
4274 async fn handle_update_worktree(
4275 this: Model<Self>,
4276 envelope: TypedEnvelope<proto::UpdateWorktree>,
4277 mut cx: AsyncAppContext,
4278 ) -> Result<()> {
4279 this.update(&mut cx, |this, cx| {
4280 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4281 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4282 worktree.update(cx, |worktree, _| {
4283 let worktree = worktree.as_remote_mut().unwrap();
4284 worktree.update_from_remote(envelope.payload);
4285 });
4286 }
4287 Ok(())
4288 })?
4289 }
4290
4291 async fn handle_update_buffer(
4292 this: Model<Self>,
4293 envelope: TypedEnvelope<proto::UpdateBuffer>,
4294 cx: AsyncAppContext,
4295 ) -> Result<proto::Ack> {
4296 let buffer_store = this.read_with(&cx, |this, cx| {
4297 if let Some(ssh) = &this.ssh_session {
4298 let mut payload = envelope.payload.clone();
4299 payload.project_id = 0;
4300 cx.background_executor()
4301 .spawn(ssh.request(payload))
4302 .detach_and_log_err(cx);
4303 }
4304 this.buffer_store.clone()
4305 })?;
4306 BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4307 }
4308
4309 fn retain_remotely_created_buffers(
4310 &mut self,
4311 cx: &mut ModelContext<Self>,
4312 ) -> RemotelyCreatedBufferGuard {
4313 {
4314 let mut remotely_created_buffers = self.remotely_created_buffers.lock();
4315 if remotely_created_buffers.retain_count == 0 {
4316 remotely_created_buffers.buffers = self.buffer_store.read(cx).buffers().collect();
4317 }
4318 remotely_created_buffers.retain_count += 1;
4319 }
4320 RemotelyCreatedBufferGuard {
4321 remote_buffers: Arc::downgrade(&self.remotely_created_buffers),
4322 }
4323 }
4324
4325 async fn handle_create_buffer_for_peer(
4326 this: Model<Self>,
4327 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4328 mut cx: AsyncAppContext,
4329 ) -> Result<()> {
4330 this.update(&mut cx, |this, cx| {
4331 this.buffer_store.update(cx, |buffer_store, cx| {
4332 buffer_store.handle_create_buffer_for_peer(
4333 envelope,
4334 this.replica_id(),
4335 this.capability(),
4336 cx,
4337 )
4338 })
4339 })?
4340 }
4341
4342 async fn handle_reload_buffers(
4343 this: Model<Self>,
4344 envelope: TypedEnvelope<proto::ReloadBuffers>,
4345 mut cx: AsyncAppContext,
4346 ) -> Result<proto::ReloadBuffersResponse> {
4347 let sender_id = envelope.original_sender_id()?;
4348 let reload = this.update(&mut cx, |this, cx| {
4349 let mut buffers = HashSet::default();
4350 for buffer_id in &envelope.payload.buffer_ids {
4351 let buffer_id = BufferId::new(*buffer_id)?;
4352 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
4353 }
4354 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
4355 })??;
4356
4357 let project_transaction = reload.await?;
4358 let project_transaction = this.update(&mut cx, |this, cx| {
4359 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4360 })?;
4361 Ok(proto::ReloadBuffersResponse {
4362 transaction: Some(project_transaction),
4363 })
4364 }
4365
4366 async fn handle_synchronize_buffers(
4367 this: Model<Self>,
4368 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4369 mut cx: AsyncAppContext,
4370 ) -> Result<proto::SynchronizeBuffersResponse> {
4371 let response = this.update(&mut cx, |this, cx| {
4372 let client = this.client.clone();
4373 this.buffer_store.update(cx, |this, cx| {
4374 this.handle_synchronize_buffers(envelope, cx, client)
4375 })
4376 })??;
4377
4378 Ok(response)
4379 }
4380
4381 async fn handle_format_buffers(
4382 this: Model<Self>,
4383 envelope: TypedEnvelope<proto::FormatBuffers>,
4384 mut cx: AsyncAppContext,
4385 ) -> Result<proto::FormatBuffersResponse> {
4386 let sender_id = envelope.original_sender_id()?;
4387 let format = this.update(&mut cx, |this, cx| {
4388 let mut buffers = HashSet::default();
4389 for buffer_id in &envelope.payload.buffer_ids {
4390 let buffer_id = BufferId::new(*buffer_id)?;
4391 buffers.insert(this.buffer_store.read(cx).get_existing(buffer_id)?);
4392 }
4393 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
4394 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
4395 })??;
4396
4397 let project_transaction = format.await?;
4398 let project_transaction = this.update(&mut cx, |this, cx| {
4399 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4400 })?;
4401 Ok(proto::FormatBuffersResponse {
4402 transaction: Some(project_transaction),
4403 })
4404 }
4405
4406 async fn handle_task_context_for_location(
4407 project: Model<Self>,
4408 envelope: TypedEnvelope<proto::TaskContextForLocation>,
4409 mut cx: AsyncAppContext,
4410 ) -> Result<proto::TaskContext> {
4411 let location = envelope
4412 .payload
4413 .location
4414 .context("no location given for task context handling")?;
4415 let location = cx
4416 .update(|cx| deserialize_location(&project, location, cx))?
4417 .await?;
4418 let context_task = project.update(&mut cx, |project, cx| {
4419 let captured_variables = {
4420 let mut variables = TaskVariables::default();
4421 for range in location
4422 .buffer
4423 .read(cx)
4424 .snapshot()
4425 .runnable_ranges(location.range.clone())
4426 {
4427 for (capture_name, value) in range.extra_captures {
4428 variables.insert(VariableName::Custom(capture_name.into()), value);
4429 }
4430 }
4431 variables
4432 };
4433 project.task_context_for_location(captured_variables, location, cx)
4434 })?;
4435 let task_context = context_task.await.unwrap_or_default();
4436 Ok(proto::TaskContext {
4437 project_env: task_context.project_env.into_iter().collect(),
4438 cwd: task_context
4439 .cwd
4440 .map(|cwd| cwd.to_string_lossy().to_string()),
4441 task_variables: task_context
4442 .task_variables
4443 .into_iter()
4444 .map(|(variable_name, variable_value)| (variable_name.to_string(), variable_value))
4445 .collect(),
4446 })
4447 }
4448
4449 async fn handle_task_templates(
4450 project: Model<Self>,
4451 envelope: TypedEnvelope<proto::TaskTemplates>,
4452 mut cx: AsyncAppContext,
4453 ) -> Result<proto::TaskTemplatesResponse> {
4454 let worktree = envelope.payload.worktree_id.map(WorktreeId::from_proto);
4455 let location = match envelope.payload.location {
4456 Some(location) => Some(
4457 cx.update(|cx| deserialize_location(&project, location, cx))?
4458 .await
4459 .context("task templates request location deserializing")?,
4460 ),
4461 None => None,
4462 };
4463
4464 let templates = project
4465 .update(&mut cx, |project, cx| {
4466 project.task_templates(worktree, location, cx)
4467 })?
4468 .await
4469 .context("receiving task templates")?
4470 .into_iter()
4471 .map(|(kind, template)| {
4472 let kind = Some(match kind {
4473 TaskSourceKind::UserInput => proto::task_source_kind::Kind::UserInput(
4474 proto::task_source_kind::UserInput {},
4475 ),
4476 TaskSourceKind::Worktree {
4477 id,
4478 abs_path,
4479 id_base,
4480 } => {
4481 proto::task_source_kind::Kind::Worktree(proto::task_source_kind::Worktree {
4482 id: id.to_proto(),
4483 abs_path: abs_path.to_string_lossy().to_string(),
4484 id_base: id_base.to_string(),
4485 })
4486 }
4487 TaskSourceKind::AbsPath { id_base, abs_path } => {
4488 proto::task_source_kind::Kind::AbsPath(proto::task_source_kind::AbsPath {
4489 abs_path: abs_path.to_string_lossy().to_string(),
4490 id_base: id_base.to_string(),
4491 })
4492 }
4493 TaskSourceKind::Language { name } => {
4494 proto::task_source_kind::Kind::Language(proto::task_source_kind::Language {
4495 name: name.to_string(),
4496 })
4497 }
4498 });
4499 let kind = Some(proto::TaskSourceKind { kind });
4500 let template = Some(proto::TaskTemplate {
4501 label: template.label,
4502 command: template.command,
4503 args: template.args,
4504 env: template.env.into_iter().collect(),
4505 cwd: template.cwd,
4506 use_new_terminal: template.use_new_terminal,
4507 allow_concurrent_runs: template.allow_concurrent_runs,
4508 reveal: match template.reveal {
4509 RevealStrategy::Always => proto::RevealStrategy::RevealAlways as i32,
4510 RevealStrategy::Never => proto::RevealStrategy::RevealNever as i32,
4511 },
4512 hide: match template.hide {
4513 HideStrategy::Always => proto::HideStrategy::HideAlways as i32,
4514 HideStrategy::Never => proto::HideStrategy::HideNever as i32,
4515 HideStrategy::OnSuccess => proto::HideStrategy::HideOnSuccess as i32,
4516 },
4517 shell: Some(proto::Shell {
4518 shell_type: Some(match template.shell {
4519 Shell::System => proto::shell::ShellType::System(proto::System {}),
4520 Shell::Program(program) => proto::shell::ShellType::Program(program),
4521 Shell::WithArguments { program, args } => {
4522 proto::shell::ShellType::WithArguments(
4523 proto::shell::WithArguments { program, args },
4524 )
4525 }
4526 }),
4527 }),
4528 tags: template.tags,
4529 });
4530 proto::TemplatePair { kind, template }
4531 })
4532 .collect();
4533
4534 Ok(proto::TaskTemplatesResponse { templates })
4535 }
4536
4537 async fn handle_search_project(
4538 this: Model<Self>,
4539 envelope: TypedEnvelope<proto::SearchProject>,
4540 mut cx: AsyncAppContext,
4541 ) -> Result<proto::SearchProjectResponse> {
4542 let peer_id = envelope.original_sender_id()?;
4543 let query = SearchQuery::from_proto_v1(envelope.payload)?;
4544 let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
4545
4546 cx.spawn(move |mut cx| async move {
4547 let mut locations = Vec::new();
4548 let mut limit_reached = false;
4549 while let Some(result) = result.next().await {
4550 match result {
4551 SearchResult::Buffer { buffer, ranges } => {
4552 for range in ranges {
4553 let start = serialize_anchor(&range.start);
4554 let end = serialize_anchor(&range.end);
4555 let buffer_id = this.update(&mut cx, |this, cx| {
4556 this.create_buffer_for_peer(&buffer, peer_id, cx).into()
4557 })?;
4558 locations.push(proto::Location {
4559 buffer_id,
4560 start: Some(start),
4561 end: Some(end),
4562 });
4563 }
4564 }
4565 SearchResult::LimitReached => limit_reached = true,
4566 }
4567 }
4568 Ok(proto::SearchProjectResponse {
4569 locations,
4570 limit_reached,
4571 // will restart
4572 })
4573 })
4574 .await
4575 }
4576
4577 async fn handle_search_candidate_buffers(
4578 this: Model<Self>,
4579 envelope: TypedEnvelope<proto::FindSearchCandidates>,
4580 mut cx: AsyncAppContext,
4581 ) -> Result<proto::FindSearchCandidatesResponse> {
4582 let peer_id = envelope.original_sender_id()?;
4583 let message = envelope.payload;
4584 let query = SearchQuery::from_proto(
4585 message
4586 .query
4587 .ok_or_else(|| anyhow!("missing query field"))?,
4588 )?;
4589 let mut results = this.update(&mut cx, |this, cx| {
4590 this.search_for_candidate_buffers(&query, message.limit as _, cx)
4591 })?;
4592
4593 let mut response = proto::FindSearchCandidatesResponse {
4594 buffer_ids: Vec::new(),
4595 };
4596
4597 while let Some(buffer) = results.next().await {
4598 this.update(&mut cx, |this, cx| {
4599 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4600 response.buffer_ids.push(buffer_id.to_proto());
4601 })?;
4602 }
4603
4604 Ok(response)
4605 }
4606
4607 async fn handle_open_buffer_by_id(
4608 this: Model<Self>,
4609 envelope: TypedEnvelope<proto::OpenBufferById>,
4610 mut cx: AsyncAppContext,
4611 ) -> Result<proto::OpenBufferResponse> {
4612 let peer_id = envelope.original_sender_id()?;
4613 let buffer_id = BufferId::new(envelope.payload.id)?;
4614 let buffer = this
4615 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4616 .await?;
4617 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4618 }
4619
4620 async fn handle_open_buffer_by_path(
4621 this: Model<Self>,
4622 envelope: TypedEnvelope<proto::OpenBufferByPath>,
4623 mut cx: AsyncAppContext,
4624 ) -> Result<proto::OpenBufferResponse> {
4625 let peer_id = envelope.original_sender_id()?;
4626 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4627 let open_buffer = this.update(&mut cx, |this, cx| {
4628 this.open_buffer(
4629 ProjectPath {
4630 worktree_id,
4631 path: PathBuf::from(envelope.payload.path).into(),
4632 },
4633 cx,
4634 )
4635 })?;
4636
4637 let buffer = open_buffer.await?;
4638 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4639 }
4640
4641 async fn handle_open_new_buffer(
4642 this: Model<Self>,
4643 envelope: TypedEnvelope<proto::OpenNewBuffer>,
4644 mut cx: AsyncAppContext,
4645 ) -> Result<proto::OpenBufferResponse> {
4646 let buffer = this.update(&mut cx, |this, cx| this.create_local_buffer("", None, cx))?;
4647 let peer_id = envelope.original_sender_id()?;
4648
4649 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4650 }
4651
4652 fn respond_to_open_buffer_request(
4653 this: Model<Self>,
4654 buffer: Model<Buffer>,
4655 peer_id: proto::PeerId,
4656 cx: &mut AsyncAppContext,
4657 ) -> Result<proto::OpenBufferResponse> {
4658 this.update(cx, |this, cx| {
4659 let is_private = buffer
4660 .read(cx)
4661 .file()
4662 .map(|f| f.is_private())
4663 .unwrap_or_default();
4664 if is_private {
4665 Err(anyhow!(ErrorCode::UnsharedItem))
4666 } else {
4667 Ok(proto::OpenBufferResponse {
4668 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4669 })
4670 }
4671 })?
4672 }
4673
4674 fn serialize_project_transaction_for_peer(
4675 &mut self,
4676 project_transaction: ProjectTransaction,
4677 peer_id: proto::PeerId,
4678 cx: &mut AppContext,
4679 ) -> proto::ProjectTransaction {
4680 self.buffer_store.update(cx, |buffer_store, cx| {
4681 buffer_store.serialize_project_transaction_for_peer(project_transaction, peer_id, cx)
4682 })
4683 }
4684
4685 fn create_buffer_for_peer(
4686 &mut self,
4687 buffer: &Model<Buffer>,
4688 peer_id: proto::PeerId,
4689 cx: &mut AppContext,
4690 ) -> BufferId {
4691 self.buffer_store
4692 .update(cx, |buffer_store, cx| {
4693 buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4694 })
4695 .detach_and_log_err(cx);
4696 buffer.read(cx).remote_id()
4697 }
4698
4699 fn wait_for_remote_buffer(
4700 &mut self,
4701 id: BufferId,
4702 cx: &mut ModelContext<Self>,
4703 ) -> Task<Result<Model<Buffer>>> {
4704 self.buffer_store.update(cx, |buffer_store, cx| {
4705 buffer_store.wait_for_remote_buffer(id, cx)
4706 })
4707 }
4708
4709 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
4710 let project_id = match self.client_state {
4711 ProjectClientState::Remote {
4712 sharing_has_stopped,
4713 remote_id,
4714 ..
4715 } => {
4716 if sharing_has_stopped {
4717 return Task::ready(Err(anyhow!(
4718 "can't synchronize remote buffers on a readonly project"
4719 )));
4720 } else {
4721 remote_id
4722 }
4723 }
4724 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4725 return Task::ready(Err(anyhow!(
4726 "can't synchronize remote buffers on a local project"
4727 )))
4728 }
4729 };
4730
4731 let client = self.client.clone();
4732 cx.spawn(move |this, mut cx| async move {
4733 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
4734 this.buffer_store.read(cx).buffer_version_info(cx)
4735 })?;
4736 let response = client
4737 .request(proto::SynchronizeBuffers {
4738 project_id,
4739 buffers,
4740 })
4741 .await?;
4742
4743 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
4744 response
4745 .buffers
4746 .into_iter()
4747 .map(|buffer| {
4748 let client = client.clone();
4749 let buffer_id = match BufferId::new(buffer.id) {
4750 Ok(id) => id,
4751 Err(e) => {
4752 return Task::ready(Err(e));
4753 }
4754 };
4755 let remote_version = language::proto::deserialize_version(&buffer.version);
4756 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4757 let operations =
4758 buffer.read(cx).serialize_ops(Some(remote_version), cx);
4759 cx.background_executor().spawn(async move {
4760 let operations = operations.await;
4761 for chunk in split_operations(operations) {
4762 client
4763 .request(proto::UpdateBuffer {
4764 project_id,
4765 buffer_id: buffer_id.into(),
4766 operations: chunk,
4767 })
4768 .await?;
4769 }
4770 anyhow::Ok(())
4771 })
4772 } else {
4773 Task::ready(Ok(()))
4774 }
4775 })
4776 .collect::<Vec<_>>()
4777 })?;
4778
4779 // Any incomplete buffers have open requests waiting. Request that the host sends
4780 // creates these buffers for us again to unblock any waiting futures.
4781 for id in incomplete_buffer_ids {
4782 cx.background_executor()
4783 .spawn(client.request(proto::OpenBufferById {
4784 project_id,
4785 id: id.into(),
4786 }))
4787 .detach();
4788 }
4789
4790 futures::future::join_all(send_updates_for_buffers)
4791 .await
4792 .into_iter()
4793 .collect()
4794 })
4795 }
4796
4797 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
4798 self.worktrees(cx)
4799 .map(|worktree| {
4800 let worktree = worktree.read(cx);
4801 proto::WorktreeMetadata {
4802 id: worktree.id().to_proto(),
4803 root_name: worktree.root_name().into(),
4804 visible: worktree.is_visible(),
4805 abs_path: worktree.abs_path().to_string_lossy().into(),
4806 }
4807 })
4808 .collect()
4809 }
4810
4811 fn set_worktrees_from_proto(
4812 &mut self,
4813 worktrees: Vec<proto::WorktreeMetadata>,
4814 cx: &mut ModelContext<Project>,
4815 ) -> Result<()> {
4816 self.metadata_changed(cx);
4817 self.worktree_store.update(cx, |worktree_store, cx| {
4818 worktree_store.set_worktrees_from_proto(
4819 worktrees,
4820 self.replica_id(),
4821 self.remote_id().ok_or_else(|| anyhow!("invalid project"))?,
4822 self.client.clone().into(),
4823 cx,
4824 )
4825 })
4826 }
4827
4828 fn set_collaborators_from_proto(
4829 &mut self,
4830 messages: Vec<proto::Collaborator>,
4831 cx: &mut ModelContext<Self>,
4832 ) -> Result<()> {
4833 let mut collaborators = HashMap::default();
4834 for message in messages {
4835 let collaborator = Collaborator::from_proto(message)?;
4836 collaborators.insert(collaborator.peer_id, collaborator);
4837 }
4838 for old_peer_id in self.collaborators.keys() {
4839 if !collaborators.contains_key(old_peer_id) {
4840 cx.emit(Event::CollaboratorLeft(*old_peer_id));
4841 }
4842 }
4843 self.collaborators = collaborators;
4844 Ok(())
4845 }
4846
4847 pub fn language_servers<'a>(
4848 &'a self,
4849 cx: &'a AppContext,
4850 ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
4851 self.lsp_store.read(cx).language_servers()
4852 }
4853
4854 pub fn supplementary_language_servers<'a>(
4855 &'a self,
4856 cx: &'a AppContext,
4857 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4858 self.lsp_store.read(cx).supplementary_language_servers()
4859 }
4860
4861 pub fn language_server_adapter_for_id(
4862 &self,
4863 id: LanguageServerId,
4864 cx: &AppContext,
4865 ) -> Option<Arc<CachedLspAdapter>> {
4866 self.lsp_store.read(cx).language_server_adapter_for_id(id)
4867 }
4868
4869 pub fn language_server_for_id(
4870 &self,
4871 id: LanguageServerId,
4872 cx: &AppContext,
4873 ) -> Option<Arc<LanguageServer>> {
4874 self.lsp_store.read(cx).language_server_for_id(id)
4875 }
4876
4877 pub fn language_servers_for_buffer<'a>(
4878 &'a self,
4879 buffer: &'a Buffer,
4880 cx: &'a AppContext,
4881 ) -> impl Iterator<Item = (&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
4882 self.lsp_store
4883 .read(cx)
4884 .language_servers_for_buffer(buffer, cx)
4885 }
4886
4887 pub fn language_server_for_buffer<'a>(
4888 &'a self,
4889 buffer: &'a Buffer,
4890 server_id: LanguageServerId,
4891 cx: &'a AppContext,
4892 ) -> Option<(&'a Arc<CachedLspAdapter>, &'a Arc<LanguageServer>)> {
4893 self.lsp_store
4894 .read(cx)
4895 .language_server_for_buffer(buffer, server_id, cx)
4896 }
4897
4898 pub fn task_context_for_location(
4899 &self,
4900 captured_variables: TaskVariables,
4901 location: Location,
4902 cx: &mut ModelContext<'_, Project>,
4903 ) -> Task<Option<TaskContext>> {
4904 if self.is_local_or_ssh() {
4905 let (worktree_id, worktree_abs_path) = if let Some(worktree) = self.task_worktree(cx) {
4906 (
4907 Some(worktree.read(cx).id()),
4908 Some(worktree.read(cx).abs_path()),
4909 )
4910 } else {
4911 (None, None)
4912 };
4913
4914 cx.spawn(|project, mut cx| async move {
4915 let mut task_variables = cx
4916 .update(|cx| {
4917 combine_task_variables(
4918 captured_variables,
4919 location,
4920 BasicContextProvider::new(project.upgrade()?),
4921 cx,
4922 )
4923 .log_err()
4924 })
4925 .ok()
4926 .flatten()?;
4927 // Remove all custom entries starting with _, as they're not intended for use by the end user.
4928 task_variables.sweep();
4929
4930 let project_env = project
4931 .update(&mut cx, |project, cx| {
4932 let worktree_abs_path = worktree_abs_path.clone();
4933 project.environment.update(cx, |environment, cx| {
4934 environment.get_environment(worktree_id, worktree_abs_path, cx)
4935 })
4936 })
4937 .ok()?
4938 .await;
4939
4940 Some(TaskContext {
4941 project_env: project_env.unwrap_or_default(),
4942 cwd: worktree_abs_path.map(|p| p.to_path_buf()),
4943 task_variables,
4944 })
4945 })
4946 } else if let Some(project_id) = self
4947 .remote_id()
4948 .filter(|_| self.ssh_connection_string(cx).is_some())
4949 {
4950 let task_context = self.client().request(proto::TaskContextForLocation {
4951 project_id,
4952 location: Some(proto::Location {
4953 buffer_id: location.buffer.read(cx).remote_id().into(),
4954 start: Some(serialize_anchor(&location.range.start)),
4955 end: Some(serialize_anchor(&location.range.end)),
4956 }),
4957 });
4958 cx.background_executor().spawn(async move {
4959 let task_context = task_context.await.log_err()?;
4960 Some(TaskContext {
4961 project_env: task_context.project_env.into_iter().collect(),
4962 cwd: task_context.cwd.map(PathBuf::from),
4963 task_variables: task_context
4964 .task_variables
4965 .into_iter()
4966 .filter_map(
4967 |(variable_name, variable_value)| match variable_name.parse() {
4968 Ok(variable_name) => Some((variable_name, variable_value)),
4969 Err(()) => {
4970 log::error!("Unknown variable name: {variable_name}");
4971 None
4972 }
4973 },
4974 )
4975 .collect(),
4976 })
4977 })
4978 } else {
4979 Task::ready(None)
4980 }
4981 }
4982
4983 pub fn task_templates(
4984 &self,
4985 worktree: Option<WorktreeId>,
4986 location: Option<Location>,
4987 cx: &mut ModelContext<Self>,
4988 ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
4989 if self.is_local_or_ssh() {
4990 let (file, language) = location
4991 .map(|location| {
4992 let buffer = location.buffer.read(cx);
4993 (
4994 buffer.file().cloned(),
4995 buffer.language_at(location.range.start),
4996 )
4997 })
4998 .unwrap_or_default();
4999 Task::ready(Ok(self
5000 .task_inventory()
5001 .read(cx)
5002 .list_tasks(file, language, worktree, cx)))
5003 } else if let Some(project_id) = self
5004 .remote_id()
5005 .filter(|_| self.ssh_connection_string(cx).is_some())
5006 {
5007 let remote_templates =
5008 self.query_remote_task_templates(project_id, worktree, location.as_ref(), cx);
5009 cx.background_executor().spawn(remote_templates)
5010 } else {
5011 Task::ready(Ok(Vec::new()))
5012 }
5013 }
5014
5015 pub fn query_remote_task_templates(
5016 &self,
5017 project_id: u64,
5018 worktree: Option<WorktreeId>,
5019 location: Option<&Location>,
5020 cx: &AppContext,
5021 ) -> Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>> {
5022 let client = self.client();
5023 let location = location.map(|location| serialize_location(location, cx));
5024 cx.spawn(|_| async move {
5025 let response = client
5026 .request(proto::TaskTemplates {
5027 project_id,
5028 worktree_id: worktree.map(|id| id.to_proto()),
5029 location,
5030 })
5031 .await?;
5032
5033 Ok(response
5034 .templates
5035 .into_iter()
5036 .filter_map(|template_pair| {
5037 let task_source_kind = match template_pair.kind?.kind? {
5038 proto::task_source_kind::Kind::UserInput(_) => TaskSourceKind::UserInput,
5039 proto::task_source_kind::Kind::Worktree(worktree) => {
5040 TaskSourceKind::Worktree {
5041 id: WorktreeId::from_proto(worktree.id),
5042 abs_path: PathBuf::from(worktree.abs_path),
5043 id_base: Cow::Owned(worktree.id_base),
5044 }
5045 }
5046 proto::task_source_kind::Kind::AbsPath(abs_path) => {
5047 TaskSourceKind::AbsPath {
5048 id_base: Cow::Owned(abs_path.id_base),
5049 abs_path: PathBuf::from(abs_path.abs_path),
5050 }
5051 }
5052 proto::task_source_kind::Kind::Language(language) => {
5053 TaskSourceKind::Language {
5054 name: language.name.into(),
5055 }
5056 }
5057 };
5058
5059 let proto_template = template_pair.template?;
5060 let reveal = match proto::RevealStrategy::from_i32(proto_template.reveal)
5061 .unwrap_or(proto::RevealStrategy::RevealAlways)
5062 {
5063 proto::RevealStrategy::RevealAlways => RevealStrategy::Always,
5064 proto::RevealStrategy::RevealNever => RevealStrategy::Never,
5065 };
5066 let hide = match proto::HideStrategy::from_i32(proto_template.hide)
5067 .unwrap_or(proto::HideStrategy::HideNever)
5068 {
5069 proto::HideStrategy::HideAlways => HideStrategy::Always,
5070 proto::HideStrategy::HideNever => HideStrategy::Never,
5071 proto::HideStrategy::HideOnSuccess => HideStrategy::OnSuccess,
5072 };
5073 let shell = match proto_template
5074 .shell
5075 .and_then(|shell| shell.shell_type)
5076 .unwrap_or(proto::shell::ShellType::System(proto::System {}))
5077 {
5078 proto::shell::ShellType::System(_) => Shell::System,
5079 proto::shell::ShellType::Program(program) => Shell::Program(program),
5080 proto::shell::ShellType::WithArguments(with_arguments) => {
5081 Shell::WithArguments {
5082 program: with_arguments.program,
5083 args: with_arguments.args,
5084 }
5085 }
5086 };
5087 let task_template = TaskTemplate {
5088 label: proto_template.label,
5089 command: proto_template.command,
5090 args: proto_template.args,
5091 env: proto_template.env.into_iter().collect(),
5092 cwd: proto_template.cwd,
5093 use_new_terminal: proto_template.use_new_terminal,
5094 allow_concurrent_runs: proto_template.allow_concurrent_runs,
5095 reveal,
5096 hide,
5097 shell,
5098 tags: proto_template.tags,
5099 };
5100 Some((task_source_kind, task_template))
5101 })
5102 .collect())
5103 })
5104 }
5105
5106 fn task_worktree(&self, cx: &AppContext) -> Option<Model<Worktree>> {
5107 let available_worktrees = self
5108 .worktrees(cx)
5109 .filter(|worktree| {
5110 let worktree = worktree.read(cx);
5111 worktree.is_visible()
5112 && worktree.is_local()
5113 && worktree.root_entry().map_or(false, |e| e.is_dir())
5114 })
5115 .collect::<Vec<_>>();
5116
5117 match available_worktrees.len() {
5118 0 => None,
5119 1 => Some(available_worktrees[0].clone()),
5120 _ => self.active_entry().and_then(|entry_id| {
5121 available_worktrees.into_iter().find_map(|worktree| {
5122 if worktree.read(cx).contains_entry(entry_id) {
5123 Some(worktree)
5124 } else {
5125 None
5126 }
5127 })
5128 }),
5129 }
5130 }
5131}
5132
5133fn combine_task_variables(
5134 mut captured_variables: TaskVariables,
5135 location: Location,
5136 baseline: BasicContextProvider,
5137 cx: &mut AppContext,
5138) -> anyhow::Result<TaskVariables> {
5139 let language_context_provider = location
5140 .buffer
5141 .read(cx)
5142 .language()
5143 .and_then(|language| language.context_provider());
5144 let baseline = baseline
5145 .build_context(&captured_variables, &location, cx)
5146 .context("building basic default context")?;
5147 captured_variables.extend(baseline);
5148 if let Some(provider) = language_context_provider {
5149 captured_variables.extend(
5150 provider
5151 .build_context(&captured_variables, &location, cx)
5152 .context("building provider context")?,
5153 );
5154 }
5155 Ok(captured_variables)
5156}
5157
5158fn deserialize_code_actions(code_actions: &HashMap<String, bool>) -> Vec<lsp::CodeActionKind> {
5159 code_actions
5160 .iter()
5161 .flat_map(|(kind, enabled)| {
5162 if *enabled {
5163 Some(kind.clone().into())
5164 } else {
5165 None
5166 }
5167 })
5168 .collect()
5169}
5170
5171pub struct PathMatchCandidateSet {
5172 pub snapshot: Snapshot,
5173 pub include_ignored: bool,
5174 pub include_root_name: bool,
5175 pub candidates: Candidates,
5176}
5177
5178pub enum Candidates {
5179 /// Only consider directories.
5180 Directories,
5181 /// Only consider files.
5182 Files,
5183 /// Consider directories and files.
5184 Entries,
5185}
5186
5187impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5188 type Candidates = PathMatchCandidateSetIter<'a>;
5189
5190 fn id(&self) -> usize {
5191 self.snapshot.id().to_usize()
5192 }
5193
5194 fn len(&self) -> usize {
5195 match self.candidates {
5196 Candidates::Files => {
5197 if self.include_ignored {
5198 self.snapshot.file_count()
5199 } else {
5200 self.snapshot.visible_file_count()
5201 }
5202 }
5203
5204 Candidates::Directories => {
5205 if self.include_ignored {
5206 self.snapshot.dir_count()
5207 } else {
5208 self.snapshot.visible_dir_count()
5209 }
5210 }
5211
5212 Candidates::Entries => {
5213 if self.include_ignored {
5214 self.snapshot.entry_count()
5215 } else {
5216 self.snapshot.visible_entry_count()
5217 }
5218 }
5219 }
5220 }
5221
5222 fn prefix(&self) -> Arc<str> {
5223 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5224 self.snapshot.root_name().into()
5225 } else if self.include_root_name {
5226 format!("{}/", self.snapshot.root_name()).into()
5227 } else {
5228 Arc::default()
5229 }
5230 }
5231
5232 fn candidates(&'a self, start: usize) -> Self::Candidates {
5233 PathMatchCandidateSetIter {
5234 traversal: match self.candidates {
5235 Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5236 Candidates::Files => self.snapshot.files(self.include_ignored, start),
5237 Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5238 },
5239 }
5240 }
5241}
5242
5243pub struct PathMatchCandidateSetIter<'a> {
5244 traversal: Traversal<'a>,
5245}
5246
5247impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5248 type Item = fuzzy::PathMatchCandidate<'a>;
5249
5250 fn next(&mut self) -> Option<Self::Item> {
5251 self.traversal
5252 .next()
5253 .map(|entry| fuzzy::PathMatchCandidate {
5254 is_dir: entry.kind.is_dir(),
5255 path: &entry.path,
5256 char_bag: entry.char_bag,
5257 })
5258 }
5259}
5260
5261impl EventEmitter<Event> for Project {}
5262
5263impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5264 fn from(val: &'a ProjectPath) -> Self {
5265 SettingsLocation {
5266 worktree_id: val.worktree_id,
5267 path: val.path.as_ref(),
5268 }
5269 }
5270}
5271
5272impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5273 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5274 Self {
5275 worktree_id,
5276 path: path.as_ref().into(),
5277 }
5278 }
5279}
5280
5281pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5282 let mut path_components = path.components();
5283 let mut base_components = base.components();
5284 let mut components: Vec<Component> = Vec::new();
5285 loop {
5286 match (path_components.next(), base_components.next()) {
5287 (None, None) => break,
5288 (Some(a), None) => {
5289 components.push(a);
5290 components.extend(path_components.by_ref());
5291 break;
5292 }
5293 (None, _) => components.push(Component::ParentDir),
5294 (Some(a), Some(b)) if components.is_empty() && a == b => (),
5295 (Some(a), Some(Component::CurDir)) => components.push(a),
5296 (Some(a), Some(_)) => {
5297 components.push(Component::ParentDir);
5298 for _ in base_components {
5299 components.push(Component::ParentDir);
5300 }
5301 components.push(a);
5302 components.extend(path_components.by_ref());
5303 break;
5304 }
5305 }
5306 }
5307 components.iter().map(|c| c.as_os_str()).collect()
5308}
5309
5310fn resolve_path(base: &Path, path: &Path) -> PathBuf {
5311 let mut result = base.to_path_buf();
5312 for component in path.components() {
5313 match component {
5314 Component::ParentDir => {
5315 result.pop();
5316 }
5317 Component::CurDir => (),
5318 _ => result.push(component),
5319 }
5320 }
5321 result
5322}
5323
5324/// ResolvedPath is a path that has been resolved to either a ProjectPath
5325/// or an AbsPath and that *exists*.
5326#[derive(Debug, Clone)]
5327pub enum ResolvedPath {
5328 ProjectPath(ProjectPath),
5329 AbsPath(PathBuf),
5330}
5331
5332impl Item for Buffer {
5333 fn try_open(
5334 project: &Model<Project>,
5335 path: &ProjectPath,
5336 cx: &mut AppContext,
5337 ) -> Option<Task<Result<Model<Self>>>> {
5338 Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5339 }
5340
5341 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
5342 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5343 }
5344
5345 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
5346 File::from_dyn(self.file()).map(|file| ProjectPath {
5347 worktree_id: file.worktree_id(cx),
5348 path: file.path().clone(),
5349 })
5350 }
5351}
5352
5353impl Completion {
5354 /// A key that can be used to sort completions when displaying
5355 /// them to the user.
5356 pub fn sort_key(&self) -> (usize, &str) {
5357 let kind_key = match self.lsp_completion.kind {
5358 Some(lsp::CompletionItemKind::KEYWORD) => 0,
5359 Some(lsp::CompletionItemKind::VARIABLE) => 1,
5360 _ => 2,
5361 };
5362 (kind_key, &self.label.text[self.label.filter_range.clone()])
5363 }
5364
5365 /// Whether this completion is a snippet.
5366 pub fn is_snippet(&self) -> bool {
5367 self.lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5368 }
5369}
5370
5371#[derive(Debug)]
5372pub struct NoRepositoryError {}
5373
5374impl std::fmt::Display for NoRepositoryError {
5375 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5376 write!(f, "no git repository for worktree found")
5377 }
5378}
5379
5380impl std::error::Error for NoRepositoryError {}
5381
5382fn serialize_location(location: &Location, cx: &AppContext) -> proto::Location {
5383 proto::Location {
5384 buffer_id: location.buffer.read(cx).remote_id().into(),
5385 start: Some(serialize_anchor(&location.range.start)),
5386 end: Some(serialize_anchor(&location.range.end)),
5387 }
5388}
5389
5390fn deserialize_location(
5391 project: &Model<Project>,
5392 location: proto::Location,
5393 cx: &mut AppContext,
5394) -> Task<Result<Location>> {
5395 let buffer_id = match BufferId::new(location.buffer_id) {
5396 Ok(id) => id,
5397 Err(e) => return Task::ready(Err(e)),
5398 };
5399 let buffer_task = project.update(cx, |project, cx| {
5400 project.wait_for_remote_buffer(buffer_id, cx)
5401 });
5402 cx.spawn(|_| async move {
5403 let buffer = buffer_task.await?;
5404 let start = location
5405 .start
5406 .and_then(deserialize_anchor)
5407 .context("missing task context location start")?;
5408 let end = location
5409 .end
5410 .and_then(deserialize_anchor)
5411 .context("missing task context location end")?;
5412 Ok(Location {
5413 buffer,
5414 range: start..end,
5415 })
5416 })
5417}
5418
5419pub fn sort_worktree_entries(entries: &mut [Entry]) {
5420 entries.sort_by(|entry_a, entry_b| {
5421 compare_paths(
5422 (&entry_a.path, entry_a.is_file()),
5423 (&entry_b.path, entry_b.is_file()),
5424 )
5425 });
5426}