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