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