1mod ignore;
2mod lsp_command;
3mod lsp_glob_set;
4pub mod search;
5pub mod terminals;
6pub mod worktree;
7
8#[cfg(test)]
9mod project_tests;
10
11use anyhow::{anyhow, Context, Result};
12use client::{proto, Client, TypedEnvelope, UserStore};
13use clock::ReplicaId;
14use collections::{hash_map, BTreeMap, HashMap, HashSet};
15use copilot::Copilot;
16use futures::{
17 channel::mpsc::{self, UnboundedReceiver},
18 future::{try_join_all, Shared},
19 AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
20};
21use gpui::{
22 AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, Task,
23 UpgradeModelHandle, WeakModelHandle,
24};
25use language::{
26 point_to_lsp,
27 proto::{
28 deserialize_anchor, deserialize_fingerprint, deserialize_line_ending, deserialize_version,
29 serialize_anchor, serialize_version,
30 },
31 range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CachedLspAdapter, CodeAction, CodeLabel,
32 Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Diff, Event as BufferEvent, File as _,
33 Language, LanguageRegistry, LanguageServerName, LocalFile, OffsetRangeExt, Operation, Patch,
34 PointUtf16, RopeFingerprint, TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction,
35 Unclipped,
36};
37use lsp::{
38 DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
39 DocumentHighlightKind, LanguageServer, LanguageString, MarkedString,
40};
41use lsp_command::*;
42use lsp_glob_set::LspGlobSet;
43use postage::watch;
44use rand::prelude::*;
45use search::SearchQuery;
46use serde::Serialize;
47use settings::{FormatOnSave, Formatter, Settings};
48use sha2::{Digest, Sha256};
49use similar::{ChangeTag, TextDiff};
50use std::{
51 cell::RefCell,
52 cmp::{self, Ordering},
53 convert::TryInto,
54 hash::Hash,
55 mem,
56 num::NonZeroU32,
57 ops::Range,
58 path::{Component, Path, PathBuf},
59 rc::Rc,
60 str,
61 sync::{
62 atomic::{AtomicUsize, Ordering::SeqCst},
63 Arc,
64 },
65 time::{Duration, Instant, SystemTime},
66};
67use terminals::Terminals;
68
69use util::{debug_panic, defer, merge_json_value_into, post_inc, ResultExt, TryFutureExt as _};
70
71pub use fs::*;
72pub use worktree::*;
73
74pub trait Item {
75 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
76 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
77}
78
79// Language server state is stored across 3 collections:
80// language_servers =>
81// a mapping from unique server id to LanguageServerState which can either be a task for a
82// server in the process of starting, or a running server with adapter and language server arcs
83// language_server_ids => a mapping from worktreeId and server name to the unique server id
84// language_server_statuses => a mapping from unique server id to the current server status
85//
86// Multiple worktrees can map to the same language server for example when you jump to the definition
87// of a file in the standard library. So language_server_ids is used to look up which server is active
88// for a given worktree and language server name
89//
90// When starting a language server, first the id map is checked to make sure a server isn't already available
91// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
92// the Starting variant of LanguageServerState is stored in the language_servers map.
93pub struct Project {
94 worktrees: Vec<WorktreeHandle>,
95 active_entry: Option<ProjectEntryId>,
96 buffer_changes_tx: mpsc::UnboundedSender<BufferMessage>,
97 languages: Arc<LanguageRegistry>,
98 language_servers: HashMap<usize, LanguageServerState>,
99 language_server_ids: HashMap<(WorktreeId, LanguageServerName), usize>,
100 language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
101 last_workspace_edits_by_language_server: HashMap<usize, ProjectTransaction>,
102 next_language_server_id: usize,
103 client: Arc<client::Client>,
104 next_entry_id: Arc<AtomicUsize>,
105 join_project_response_message_id: u32,
106 next_diagnostic_group_id: usize,
107 user_store: ModelHandle<UserStore>,
108 fs: Arc<dyn Fs>,
109 client_state: Option<ProjectClientState>,
110 collaborators: HashMap<proto::PeerId, Collaborator>,
111 client_subscriptions: Vec<client::Subscription>,
112 _subscriptions: Vec<gpui::Subscription>,
113 opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
114 shared_buffers: HashMap<proto::PeerId, HashSet<u64>>,
115 #[allow(clippy::type_complexity)]
116 loading_buffers_by_path: HashMap<
117 ProjectPath,
118 postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
119 >,
120 #[allow(clippy::type_complexity)]
121 loading_local_worktrees:
122 HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
123 opened_buffers: HashMap<u64, OpenBuffer>,
124 /// A mapping from a buffer ID to None means that we've started waiting for an ID but haven't finished loading it.
125 /// Used for re-issuing buffer requests when peers temporarily disconnect
126 incomplete_remote_buffers: HashMap<u64, Option<ModelHandle<Buffer>>>,
127 buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
128 buffers_being_formatted: HashSet<usize>,
129 nonce: u128,
130 _maintain_buffer_languages: Task<()>,
131 _maintain_workspace_config: Task<()>,
132 terminals: Terminals,
133 copilot_enabled: bool,
134}
135
136enum BufferMessage {
137 Operation {
138 buffer_id: u64,
139 operation: proto::Operation,
140 },
141 Resync,
142}
143
144enum LocalProjectUpdate {
145 WorktreesChanged,
146 CreateBufferForPeer {
147 peer_id: proto::PeerId,
148 buffer_id: u64,
149 },
150}
151
152enum OpenBuffer {
153 Strong(ModelHandle<Buffer>),
154 Weak(WeakModelHandle<Buffer>),
155 Operations(Vec<Operation>),
156}
157
158enum WorktreeHandle {
159 Strong(ModelHandle<Worktree>),
160 Weak(WeakModelHandle<Worktree>),
161}
162
163enum ProjectClientState {
164 Local {
165 remote_id: u64,
166 updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
167 _send_updates: Task<()>,
168 },
169 Remote {
170 sharing_has_stopped: bool,
171 remote_id: u64,
172 replica_id: ReplicaId,
173 },
174}
175
176#[derive(Clone, Debug)]
177pub struct Collaborator {
178 pub peer_id: proto::PeerId,
179 pub replica_id: ReplicaId,
180}
181
182#[derive(Clone, Debug, PartialEq, Eq)]
183pub enum Event {
184 ActiveEntryChanged(Option<ProjectEntryId>),
185 WorktreeAdded,
186 WorktreeRemoved(WorktreeId),
187 DiskBasedDiagnosticsStarted {
188 language_server_id: usize,
189 },
190 DiskBasedDiagnosticsFinished {
191 language_server_id: usize,
192 },
193 DiagnosticsUpdated {
194 path: ProjectPath,
195 language_server_id: usize,
196 },
197 RemoteIdChanged(Option<u64>),
198 DisconnectedFromHost,
199 Closed,
200 CollaboratorUpdated {
201 old_peer_id: proto::PeerId,
202 new_peer_id: proto::PeerId,
203 },
204 CollaboratorLeft(proto::PeerId),
205}
206
207pub enum LanguageServerState {
208 Starting(Task<Option<Arc<LanguageServer>>>),
209 Running {
210 language: Arc<Language>,
211 adapter: Arc<CachedLspAdapter>,
212 server: Arc<LanguageServer>,
213 watched_paths: LspGlobSet,
214 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
215 },
216}
217
218#[derive(Serialize)]
219pub struct LanguageServerStatus {
220 pub name: String,
221 pub pending_work: BTreeMap<String, LanguageServerProgress>,
222 pub has_pending_diagnostic_updates: bool,
223 progress_tokens: HashSet<String>,
224}
225
226#[derive(Clone, Debug, Serialize)]
227pub struct LanguageServerProgress {
228 pub message: Option<String>,
229 pub percentage: Option<usize>,
230 #[serde(skip_serializing)]
231 pub last_update_at: Instant,
232}
233
234#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
235pub struct ProjectPath {
236 pub worktree_id: WorktreeId,
237 pub path: Arc<Path>,
238}
239
240#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
241pub struct DiagnosticSummary {
242 pub language_server_id: usize,
243 pub error_count: usize,
244 pub warning_count: usize,
245}
246
247#[derive(Debug, Clone)]
248pub struct Location {
249 pub buffer: ModelHandle<Buffer>,
250 pub range: Range<language::Anchor>,
251}
252
253#[derive(Debug, Clone)]
254pub struct LocationLink {
255 pub origin: Option<Location>,
256 pub target: Location,
257}
258
259#[derive(Debug)]
260pub struct DocumentHighlight {
261 pub range: Range<language::Anchor>,
262 pub kind: DocumentHighlightKind,
263}
264
265#[derive(Clone, Debug)]
266pub struct Symbol {
267 pub language_server_name: LanguageServerName,
268 pub source_worktree_id: WorktreeId,
269 pub path: ProjectPath,
270 pub label: CodeLabel,
271 pub name: String,
272 pub kind: lsp::SymbolKind,
273 pub range: Range<Unclipped<PointUtf16>>,
274 pub signature: [u8; 32],
275}
276
277#[derive(Clone, Debug, PartialEq)]
278pub struct HoverBlock {
279 pub text: String,
280 pub language: Option<String>,
281}
282
283impl HoverBlock {
284 fn try_new(marked_string: MarkedString) -> Option<Self> {
285 let result = match marked_string {
286 MarkedString::LanguageString(LanguageString { language, value }) => HoverBlock {
287 text: value,
288 language: Some(language),
289 },
290 MarkedString::String(text) => HoverBlock {
291 text,
292 language: None,
293 },
294 };
295 if result.text.is_empty() {
296 None
297 } else {
298 Some(result)
299 }
300 }
301}
302
303#[derive(Debug)]
304pub struct Hover {
305 pub contents: Vec<HoverBlock>,
306 pub range: Option<Range<language::Anchor>>,
307}
308
309#[derive(Default)]
310pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
311
312impl DiagnosticSummary {
313 fn new<'a, T: 'a>(
314 language_server_id: usize,
315 diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>,
316 ) -> Self {
317 let mut this = Self {
318 language_server_id,
319 error_count: 0,
320 warning_count: 0,
321 };
322
323 for entry in diagnostics {
324 if entry.diagnostic.is_primary {
325 match entry.diagnostic.severity {
326 DiagnosticSeverity::ERROR => this.error_count += 1,
327 DiagnosticSeverity::WARNING => this.warning_count += 1,
328 _ => {}
329 }
330 }
331 }
332
333 this
334 }
335
336 pub fn is_empty(&self) -> bool {
337 self.error_count == 0 && self.warning_count == 0
338 }
339
340 pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
341 proto::DiagnosticSummary {
342 path: path.to_string_lossy().to_string(),
343 language_server_id: self.language_server_id as u64,
344 error_count: self.error_count as u32,
345 warning_count: self.warning_count as u32,
346 }
347 }
348}
349
350#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
351pub struct ProjectEntryId(usize);
352
353impl ProjectEntryId {
354 pub const MAX: Self = Self(usize::MAX);
355
356 pub fn new(counter: &AtomicUsize) -> Self {
357 Self(counter.fetch_add(1, SeqCst))
358 }
359
360 pub fn from_proto(id: u64) -> Self {
361 Self(id as usize)
362 }
363
364 pub fn to_proto(&self) -> u64 {
365 self.0 as u64
366 }
367
368 pub fn to_usize(&self) -> usize {
369 self.0
370 }
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub enum FormatTrigger {
375 Save,
376 Manual,
377}
378
379impl FormatTrigger {
380 fn from_proto(value: i32) -> FormatTrigger {
381 match value {
382 0 => FormatTrigger::Save,
383 1 => FormatTrigger::Manual,
384 _ => FormatTrigger::Save,
385 }
386 }
387}
388
389impl Project {
390 pub fn init(client: &Arc<Client>) {
391 client.add_model_message_handler(Self::handle_add_collaborator);
392 client.add_model_message_handler(Self::handle_update_project_collaborator);
393 client.add_model_message_handler(Self::handle_remove_collaborator);
394 client.add_model_message_handler(Self::handle_buffer_reloaded);
395 client.add_model_message_handler(Self::handle_buffer_saved);
396 client.add_model_message_handler(Self::handle_start_language_server);
397 client.add_model_message_handler(Self::handle_update_language_server);
398 client.add_model_message_handler(Self::handle_update_project);
399 client.add_model_message_handler(Self::handle_unshare_project);
400 client.add_model_message_handler(Self::handle_create_buffer_for_peer);
401 client.add_model_message_handler(Self::handle_update_buffer_file);
402 client.add_model_request_handler(Self::handle_update_buffer);
403 client.add_model_message_handler(Self::handle_update_diagnostic_summary);
404 client.add_model_message_handler(Self::handle_update_worktree);
405 client.add_model_request_handler(Self::handle_create_project_entry);
406 client.add_model_request_handler(Self::handle_rename_project_entry);
407 client.add_model_request_handler(Self::handle_copy_project_entry);
408 client.add_model_request_handler(Self::handle_delete_project_entry);
409 client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
410 client.add_model_request_handler(Self::handle_apply_code_action);
411 client.add_model_request_handler(Self::handle_reload_buffers);
412 client.add_model_request_handler(Self::handle_synchronize_buffers);
413 client.add_model_request_handler(Self::handle_format_buffers);
414 client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
415 client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
416 client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
417 client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
418 client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
419 client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
420 client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
421 client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
422 client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
423 client.add_model_request_handler(Self::handle_search_project);
424 client.add_model_request_handler(Self::handle_get_project_symbols);
425 client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
426 client.add_model_request_handler(Self::handle_open_buffer_by_id);
427 client.add_model_request_handler(Self::handle_open_buffer_by_path);
428 client.add_model_request_handler(Self::handle_save_buffer);
429 client.add_model_message_handler(Self::handle_update_diff_base);
430 }
431
432 pub fn local(
433 client: Arc<Client>,
434 user_store: ModelHandle<UserStore>,
435 languages: Arc<LanguageRegistry>,
436 fs: Arc<dyn Fs>,
437 cx: &mut AppContext,
438 ) -> ModelHandle<Self> {
439 cx.add_model(|cx: &mut ModelContext<Self>| {
440 let (tx, rx) = mpsc::unbounded();
441 cx.spawn_weak(|this, cx| Self::send_buffer_messages(this, rx, cx))
442 .detach();
443 Self {
444 worktrees: Default::default(),
445 buffer_changes_tx: tx,
446 collaborators: Default::default(),
447 opened_buffers: Default::default(),
448 shared_buffers: Default::default(),
449 incomplete_remote_buffers: Default::default(),
450 loading_buffers_by_path: Default::default(),
451 loading_local_worktrees: Default::default(),
452 buffer_snapshots: Default::default(),
453 join_project_response_message_id: 0,
454 client_state: None,
455 opened_buffer: watch::channel(),
456 client_subscriptions: Vec::new(),
457 _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
458 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
459 _maintain_workspace_config: Self::maintain_workspace_config(languages.clone(), cx),
460 active_entry: None,
461 languages,
462 client,
463 user_store,
464 fs,
465 next_entry_id: Default::default(),
466 next_diagnostic_group_id: Default::default(),
467 language_servers: Default::default(),
468 language_server_ids: Default::default(),
469 language_server_statuses: Default::default(),
470 last_workspace_edits_by_language_server: Default::default(),
471 buffers_being_formatted: Default::default(),
472 next_language_server_id: 0,
473 nonce: StdRng::from_entropy().gen(),
474 terminals: Terminals {
475 local_handles: Vec::new(),
476 },
477 copilot_enabled: Copilot::global(cx).is_some(),
478 }
479 })
480 }
481
482 pub async fn remote(
483 remote_id: u64,
484 client: Arc<Client>,
485 user_store: ModelHandle<UserStore>,
486 languages: Arc<LanguageRegistry>,
487 fs: Arc<dyn Fs>,
488 mut cx: AsyncAppContext,
489 ) -> Result<ModelHandle<Self>> {
490 client.authenticate_and_connect(true, &cx).await?;
491
492 let subscription = client.subscribe_to_entity(remote_id)?;
493 let response = client
494 .request_envelope(proto::JoinProject {
495 project_id: remote_id,
496 })
497 .await?;
498 let this = cx.add_model(|cx| {
499 let replica_id = response.payload.replica_id as ReplicaId;
500
501 let mut worktrees = Vec::new();
502 for worktree in response.payload.worktrees {
503 let worktree = cx.update(|cx| {
504 Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx)
505 });
506 worktrees.push(worktree);
507 }
508
509 let (tx, rx) = mpsc::unbounded();
510 cx.spawn_weak(|this, cx| Self::send_buffer_messages(this, rx, cx))
511 .detach();
512 let mut this = Self {
513 worktrees: Vec::new(),
514 buffer_changes_tx: tx,
515 loading_buffers_by_path: Default::default(),
516 opened_buffer: watch::channel(),
517 shared_buffers: Default::default(),
518 incomplete_remote_buffers: Default::default(),
519 loading_local_worktrees: Default::default(),
520 active_entry: None,
521 collaborators: Default::default(),
522 join_project_response_message_id: response.message_id,
523 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
524 _maintain_workspace_config: Self::maintain_workspace_config(languages.clone(), cx),
525 languages,
526 user_store: user_store.clone(),
527 fs,
528 next_entry_id: Default::default(),
529 next_diagnostic_group_id: Default::default(),
530 client_subscriptions: Default::default(),
531 _subscriptions: Default::default(),
532 client: client.clone(),
533 client_state: Some(ProjectClientState::Remote {
534 sharing_has_stopped: false,
535 remote_id,
536 replica_id,
537 }),
538 language_servers: Default::default(),
539 language_server_ids: Default::default(),
540 language_server_statuses: response
541 .payload
542 .language_servers
543 .into_iter()
544 .map(|server| {
545 (
546 server.id as usize,
547 LanguageServerStatus {
548 name: server.name,
549 pending_work: Default::default(),
550 has_pending_diagnostic_updates: false,
551 progress_tokens: Default::default(),
552 },
553 )
554 })
555 .collect(),
556 last_workspace_edits_by_language_server: Default::default(),
557 next_language_server_id: 0,
558 opened_buffers: Default::default(),
559 buffers_being_formatted: Default::default(),
560 buffer_snapshots: Default::default(),
561 nonce: StdRng::from_entropy().gen(),
562 terminals: Terminals {
563 local_handles: Vec::new(),
564 },
565 copilot_enabled: Copilot::global(cx).is_some(),
566 };
567 for worktree in worktrees {
568 let _ = this.add_worktree(&worktree, cx);
569 }
570 this
571 });
572 let subscription = subscription.set_model(&this, &mut cx);
573
574 let user_ids = response
575 .payload
576 .collaborators
577 .iter()
578 .map(|peer| peer.user_id)
579 .collect();
580 user_store
581 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
582 .await?;
583
584 this.update(&mut cx, |this, cx| {
585 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
586 this.client_subscriptions.push(subscription);
587 anyhow::Ok(())
588 })?;
589
590 Ok(this)
591 }
592
593 #[cfg(any(test, feature = "test-support"))]
594 pub async fn test(
595 fs: Arc<dyn Fs>,
596 root_paths: impl IntoIterator<Item = &Path>,
597 cx: &mut gpui::TestAppContext,
598 ) -> ModelHandle<Project> {
599 if !cx.read(|cx| cx.has_global::<Settings>()) {
600 cx.update(|cx| {
601 cx.set_global(Settings::test(cx));
602 });
603 }
604
605 let mut languages = LanguageRegistry::test();
606 languages.set_executor(cx.background());
607 let http_client = util::http::FakeHttpClient::with_404_response();
608 let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
609 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
610 let project =
611 cx.update(|cx| Project::local(client, user_store, Arc::new(languages), fs, cx));
612 for path in root_paths {
613 let (tree, _) = project
614 .update(cx, |project, cx| {
615 project.find_or_create_local_worktree(path, true, cx)
616 })
617 .await
618 .unwrap();
619 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
620 .await;
621 }
622 project
623 }
624
625 fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
626 let settings = cx.global::<Settings>();
627
628 let mut language_servers_to_start = Vec::new();
629 for buffer in self.opened_buffers.values() {
630 if let Some(buffer) = buffer.upgrade(cx) {
631 let buffer = buffer.read(cx);
632 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
633 {
634 if settings.enable_language_server(Some(&language.name())) {
635 let worktree = file.worktree.read(cx);
636 language_servers_to_start.push((
637 worktree.id(),
638 worktree.as_local().unwrap().abs_path().clone(),
639 language.clone(),
640 ));
641 }
642 }
643 }
644 }
645
646 let mut language_servers_to_stop = Vec::new();
647 for language in self.languages.to_vec() {
648 if let Some(lsp_adapter) = language.lsp_adapter() {
649 if !settings.enable_language_server(Some(&language.name())) {
650 let lsp_name = &lsp_adapter.name;
651 for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
652 if lsp_name == started_lsp_name {
653 language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
654 }
655 }
656 }
657 }
658 }
659
660 // Stop all newly-disabled language servers.
661 for (worktree_id, adapter_name) in language_servers_to_stop {
662 self.stop_language_server(worktree_id, adapter_name, cx)
663 .detach();
664 }
665
666 // Start all the newly-enabled language servers.
667 for (worktree_id, worktree_path, language) in language_servers_to_start {
668 self.start_language_server(worktree_id, worktree_path, language, cx);
669 }
670
671 if !self.copilot_enabled && Copilot::global(cx).is_some() {
672 self.copilot_enabled = true;
673 for buffer in self.opened_buffers.values() {
674 if let Some(buffer) = buffer.upgrade(cx) {
675 self.register_buffer_with_copilot(&buffer, cx);
676 }
677 }
678 }
679
680 cx.notify();
681 }
682
683 pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
684 self.opened_buffers
685 .get(&remote_id)
686 .and_then(|buffer| buffer.upgrade(cx))
687 }
688
689 pub fn languages(&self) -> &Arc<LanguageRegistry> {
690 &self.languages
691 }
692
693 pub fn client(&self) -> Arc<Client> {
694 self.client.clone()
695 }
696
697 pub fn user_store(&self) -> ModelHandle<UserStore> {
698 self.user_store.clone()
699 }
700
701 #[cfg(any(test, feature = "test-support"))]
702 pub fn opened_buffers(&self, cx: &AppContext) -> Vec<ModelHandle<Buffer>> {
703 self.opened_buffers
704 .values()
705 .filter_map(|b| b.upgrade(cx))
706 .collect()
707 }
708
709 #[cfg(any(test, feature = "test-support"))]
710 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
711 let path = path.into();
712 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
713 self.opened_buffers.iter().any(|(_, buffer)| {
714 if let Some(buffer) = buffer.upgrade(cx) {
715 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
716 if file.worktree == worktree && file.path() == &path.path {
717 return true;
718 }
719 }
720 }
721 false
722 })
723 } else {
724 false
725 }
726 }
727
728 pub fn fs(&self) -> &Arc<dyn Fs> {
729 &self.fs
730 }
731
732 pub fn remote_id(&self) -> Option<u64> {
733 match self.client_state.as_ref()? {
734 ProjectClientState::Local { remote_id, .. }
735 | ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
736 }
737 }
738
739 pub fn replica_id(&self) -> ReplicaId {
740 match &self.client_state {
741 Some(ProjectClientState::Remote { replica_id, .. }) => *replica_id,
742 _ => 0,
743 }
744 }
745
746 fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
747 if let Some(ProjectClientState::Local { updates_tx, .. }) = &mut self.client_state {
748 updates_tx
749 .unbounded_send(LocalProjectUpdate::WorktreesChanged)
750 .ok();
751 }
752 cx.notify();
753 }
754
755 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
756 &self.collaborators
757 }
758
759 /// Collect all worktrees, including ones that don't appear in the project panel
760 pub fn worktrees<'a>(
761 &'a self,
762 cx: &'a AppContext,
763 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
764 self.worktrees
765 .iter()
766 .filter_map(move |worktree| worktree.upgrade(cx))
767 }
768
769 /// Collect all user-visible worktrees, the ones that appear in the project panel
770 pub fn visible_worktrees<'a>(
771 &'a self,
772 cx: &'a AppContext,
773 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
774 self.worktrees.iter().filter_map(|worktree| {
775 worktree.upgrade(cx).and_then(|worktree| {
776 if worktree.read(cx).is_visible() {
777 Some(worktree)
778 } else {
779 None
780 }
781 })
782 })
783 }
784
785 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
786 self.visible_worktrees(cx)
787 .map(|tree| tree.read(cx).root_name())
788 }
789
790 pub fn worktree_for_id(
791 &self,
792 id: WorktreeId,
793 cx: &AppContext,
794 ) -> Option<ModelHandle<Worktree>> {
795 self.worktrees(cx)
796 .find(|worktree| worktree.read(cx).id() == id)
797 }
798
799 pub fn worktree_for_entry(
800 &self,
801 entry_id: ProjectEntryId,
802 cx: &AppContext,
803 ) -> Option<ModelHandle<Worktree>> {
804 self.worktrees(cx)
805 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
806 }
807
808 pub fn worktree_id_for_entry(
809 &self,
810 entry_id: ProjectEntryId,
811 cx: &AppContext,
812 ) -> Option<WorktreeId> {
813 self.worktree_for_entry(entry_id, cx)
814 .map(|worktree| worktree.read(cx).id())
815 }
816
817 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
818 paths.iter().all(|path| self.contains_path(path, cx))
819 }
820
821 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
822 for worktree in self.worktrees(cx) {
823 let worktree = worktree.read(cx).as_local();
824 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
825 return true;
826 }
827 }
828 false
829 }
830
831 pub fn create_entry(
832 &mut self,
833 project_path: impl Into<ProjectPath>,
834 is_directory: bool,
835 cx: &mut ModelContext<Self>,
836 ) -> Option<Task<Result<Entry>>> {
837 let project_path = project_path.into();
838 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
839 if self.is_local() {
840 Some(worktree.update(cx, |worktree, cx| {
841 worktree
842 .as_local_mut()
843 .unwrap()
844 .create_entry(project_path.path, is_directory, cx)
845 }))
846 } else {
847 let client = self.client.clone();
848 let project_id = self.remote_id().unwrap();
849 Some(cx.spawn_weak(|_, mut cx| async move {
850 let response = client
851 .request(proto::CreateProjectEntry {
852 worktree_id: project_path.worktree_id.to_proto(),
853 project_id,
854 path: project_path.path.to_string_lossy().into(),
855 is_directory,
856 })
857 .await?;
858 let entry = response
859 .entry
860 .ok_or_else(|| anyhow!("missing entry in response"))?;
861 worktree
862 .update(&mut cx, |worktree, cx| {
863 worktree.as_remote_mut().unwrap().insert_entry(
864 entry,
865 response.worktree_scan_id as usize,
866 cx,
867 )
868 })
869 .await
870 }))
871 }
872 }
873
874 pub fn copy_entry(
875 &mut self,
876 entry_id: ProjectEntryId,
877 new_path: impl Into<Arc<Path>>,
878 cx: &mut ModelContext<Self>,
879 ) -> Option<Task<Result<Entry>>> {
880 let worktree = self.worktree_for_entry(entry_id, cx)?;
881 let new_path = new_path.into();
882 if self.is_local() {
883 worktree.update(cx, |worktree, cx| {
884 worktree
885 .as_local_mut()
886 .unwrap()
887 .copy_entry(entry_id, new_path, cx)
888 })
889 } else {
890 let client = self.client.clone();
891 let project_id = self.remote_id().unwrap();
892
893 Some(cx.spawn_weak(|_, mut cx| async move {
894 let response = client
895 .request(proto::CopyProjectEntry {
896 project_id,
897 entry_id: entry_id.to_proto(),
898 new_path: new_path.to_string_lossy().into(),
899 })
900 .await?;
901 let entry = response
902 .entry
903 .ok_or_else(|| anyhow!("missing entry in response"))?;
904 worktree
905 .update(&mut cx, |worktree, cx| {
906 worktree.as_remote_mut().unwrap().insert_entry(
907 entry,
908 response.worktree_scan_id as usize,
909 cx,
910 )
911 })
912 .await
913 }))
914 }
915 }
916
917 pub fn rename_entry(
918 &mut self,
919 entry_id: ProjectEntryId,
920 new_path: impl Into<Arc<Path>>,
921 cx: &mut ModelContext<Self>,
922 ) -> Option<Task<Result<Entry>>> {
923 let worktree = self.worktree_for_entry(entry_id, cx)?;
924 let new_path = new_path.into();
925 if self.is_local() {
926 worktree.update(cx, |worktree, cx| {
927 worktree
928 .as_local_mut()
929 .unwrap()
930 .rename_entry(entry_id, new_path, cx)
931 })
932 } else {
933 let client = self.client.clone();
934 let project_id = self.remote_id().unwrap();
935
936 Some(cx.spawn_weak(|_, mut cx| async move {
937 let response = client
938 .request(proto::RenameProjectEntry {
939 project_id,
940 entry_id: entry_id.to_proto(),
941 new_path: new_path.to_string_lossy().into(),
942 })
943 .await?;
944 let entry = response
945 .entry
946 .ok_or_else(|| anyhow!("missing entry in response"))?;
947 worktree
948 .update(&mut cx, |worktree, cx| {
949 worktree.as_remote_mut().unwrap().insert_entry(
950 entry,
951 response.worktree_scan_id as usize,
952 cx,
953 )
954 })
955 .await
956 }))
957 }
958 }
959
960 pub fn delete_entry(
961 &mut self,
962 entry_id: ProjectEntryId,
963 cx: &mut ModelContext<Self>,
964 ) -> Option<Task<Result<()>>> {
965 let worktree = self.worktree_for_entry(entry_id, cx)?;
966 if self.is_local() {
967 worktree.update(cx, |worktree, cx| {
968 worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
969 })
970 } else {
971 let client = self.client.clone();
972 let project_id = self.remote_id().unwrap();
973 Some(cx.spawn_weak(|_, mut cx| async move {
974 let response = client
975 .request(proto::DeleteProjectEntry {
976 project_id,
977 entry_id: entry_id.to_proto(),
978 })
979 .await?;
980 worktree
981 .update(&mut cx, move |worktree, cx| {
982 worktree.as_remote_mut().unwrap().delete_entry(
983 entry_id,
984 response.worktree_scan_id as usize,
985 cx,
986 )
987 })
988 .await
989 }))
990 }
991 }
992
993 pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
994 if self.client_state.is_some() {
995 return Err(anyhow!("project was already shared"));
996 }
997 self.client_subscriptions.push(
998 self.client
999 .subscribe_to_entity(project_id)?
1000 .set_model(&cx.handle(), &mut cx.to_async()),
1001 );
1002
1003 for open_buffer in self.opened_buffers.values_mut() {
1004 match open_buffer {
1005 OpenBuffer::Strong(_) => {}
1006 OpenBuffer::Weak(buffer) => {
1007 if let Some(buffer) = buffer.upgrade(cx) {
1008 *open_buffer = OpenBuffer::Strong(buffer);
1009 }
1010 }
1011 OpenBuffer::Operations(_) => unreachable!(),
1012 }
1013 }
1014
1015 for worktree_handle in self.worktrees.iter_mut() {
1016 match worktree_handle {
1017 WorktreeHandle::Strong(_) => {}
1018 WorktreeHandle::Weak(worktree) => {
1019 if let Some(worktree) = worktree.upgrade(cx) {
1020 *worktree_handle = WorktreeHandle::Strong(worktree);
1021 }
1022 }
1023 }
1024 }
1025
1026 for (server_id, status) in &self.language_server_statuses {
1027 self.client
1028 .send(proto::StartLanguageServer {
1029 project_id,
1030 server: Some(proto::LanguageServer {
1031 id: *server_id as u64,
1032 name: status.name.clone(),
1033 }),
1034 })
1035 .log_err();
1036 }
1037
1038 let (updates_tx, mut updates_rx) = mpsc::unbounded();
1039 let client = self.client.clone();
1040 self.client_state = Some(ProjectClientState::Local {
1041 remote_id: project_id,
1042 updates_tx,
1043 _send_updates: cx.spawn_weak(move |this, mut cx| async move {
1044 while let Some(update) = updates_rx.next().await {
1045 let Some(this) = this.upgrade(&cx) else { break };
1046
1047 match update {
1048 LocalProjectUpdate::WorktreesChanged => {
1049 let worktrees = this
1050 .read_with(&cx, |this, cx| this.worktrees(cx).collect::<Vec<_>>());
1051 let update_project = this
1052 .read_with(&cx, |this, cx| {
1053 this.client.request(proto::UpdateProject {
1054 project_id,
1055 worktrees: this.worktree_metadata_protos(cx),
1056 })
1057 })
1058 .await;
1059 if update_project.is_ok() {
1060 for worktree in worktrees {
1061 worktree.update(&mut cx, |worktree, cx| {
1062 let worktree = worktree.as_local_mut().unwrap();
1063 worktree.share(project_id, cx).detach_and_log_err(cx)
1064 });
1065 }
1066 }
1067 }
1068 LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
1069 let buffer = this.update(&mut cx, |this, _| {
1070 let buffer = this.opened_buffers.get(&buffer_id).unwrap();
1071 let shared_buffers =
1072 this.shared_buffers.entry(peer_id).or_default();
1073 if shared_buffers.insert(buffer_id) {
1074 if let OpenBuffer::Strong(buffer) = buffer {
1075 Some(buffer.clone())
1076 } else {
1077 None
1078 }
1079 } else {
1080 None
1081 }
1082 });
1083
1084 let Some(buffer) = buffer else { continue };
1085 let operations =
1086 buffer.read_with(&cx, |b, cx| b.serialize_ops(None, cx));
1087 let operations = operations.await;
1088 let state = buffer.read_with(&cx, |buffer, _| buffer.to_proto());
1089
1090 let initial_state = proto::CreateBufferForPeer {
1091 project_id,
1092 peer_id: Some(peer_id),
1093 variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1094 };
1095 if client.send(initial_state).log_err().is_some() {
1096 let client = client.clone();
1097 cx.background()
1098 .spawn(async move {
1099 let mut chunks = split_operations(operations).peekable();
1100 while let Some(chunk) = chunks.next() {
1101 let is_last = chunks.peek().is_none();
1102 client.send(proto::CreateBufferForPeer {
1103 project_id,
1104 peer_id: Some(peer_id),
1105 variant: Some(
1106 proto::create_buffer_for_peer::Variant::Chunk(
1107 proto::BufferChunk {
1108 buffer_id,
1109 operations: chunk,
1110 is_last,
1111 },
1112 ),
1113 ),
1114 })?;
1115 }
1116 anyhow::Ok(())
1117 })
1118 .await
1119 .log_err();
1120 }
1121 }
1122 }
1123 }
1124 }),
1125 });
1126
1127 self.metadata_changed(cx);
1128 cx.emit(Event::RemoteIdChanged(Some(project_id)));
1129 cx.notify();
1130 Ok(())
1131 }
1132
1133 pub fn reshared(
1134 &mut self,
1135 message: proto::ResharedProject,
1136 cx: &mut ModelContext<Self>,
1137 ) -> Result<()> {
1138 self.shared_buffers.clear();
1139 self.set_collaborators_from_proto(message.collaborators, cx)?;
1140 self.metadata_changed(cx);
1141 Ok(())
1142 }
1143
1144 pub fn rejoined(
1145 &mut self,
1146 message: proto::RejoinedProject,
1147 message_id: u32,
1148 cx: &mut ModelContext<Self>,
1149 ) -> Result<()> {
1150 self.join_project_response_message_id = message_id;
1151 self.set_worktrees_from_proto(message.worktrees, cx)?;
1152 self.set_collaborators_from_proto(message.collaborators, cx)?;
1153 self.language_server_statuses = message
1154 .language_servers
1155 .into_iter()
1156 .map(|server| {
1157 (
1158 server.id as usize,
1159 LanguageServerStatus {
1160 name: server.name,
1161 pending_work: Default::default(),
1162 has_pending_diagnostic_updates: false,
1163 progress_tokens: Default::default(),
1164 },
1165 )
1166 })
1167 .collect();
1168 self.buffer_changes_tx
1169 .unbounded_send(BufferMessage::Resync)
1170 .unwrap();
1171 cx.notify();
1172 Ok(())
1173 }
1174
1175 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1176 self.unshare_internal(cx)?;
1177 self.metadata_changed(cx);
1178 cx.notify();
1179 Ok(())
1180 }
1181
1182 fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1183 if self.is_remote() {
1184 return Err(anyhow!("attempted to unshare a remote project"));
1185 }
1186
1187 if let Some(ProjectClientState::Local { remote_id, .. }) = self.client_state.take() {
1188 self.collaborators.clear();
1189 self.shared_buffers.clear();
1190 self.client_subscriptions.clear();
1191
1192 for worktree_handle in self.worktrees.iter_mut() {
1193 if let WorktreeHandle::Strong(worktree) = worktree_handle {
1194 let is_visible = worktree.update(cx, |worktree, _| {
1195 worktree.as_local_mut().unwrap().unshare();
1196 worktree.is_visible()
1197 });
1198 if !is_visible {
1199 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1200 }
1201 }
1202 }
1203
1204 for open_buffer in self.opened_buffers.values_mut() {
1205 // Wake up any tasks waiting for peers' edits to this buffer.
1206 if let Some(buffer) = open_buffer.upgrade(cx) {
1207 buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1208 }
1209
1210 if let OpenBuffer::Strong(buffer) = open_buffer {
1211 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1212 }
1213 }
1214
1215 self.client.send(proto::UnshareProject {
1216 project_id: remote_id,
1217 })?;
1218
1219 Ok(())
1220 } else {
1221 Err(anyhow!("attempted to unshare an unshared project"))
1222 }
1223 }
1224
1225 pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1226 self.disconnected_from_host_internal(cx);
1227 cx.emit(Event::DisconnectedFromHost);
1228 cx.notify();
1229 }
1230
1231 fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1232 if let Some(ProjectClientState::Remote {
1233 sharing_has_stopped,
1234 ..
1235 }) = &mut self.client_state
1236 {
1237 *sharing_has_stopped = true;
1238
1239 self.collaborators.clear();
1240
1241 for worktree in &self.worktrees {
1242 if let Some(worktree) = worktree.upgrade(cx) {
1243 worktree.update(cx, |worktree, _| {
1244 if let Some(worktree) = worktree.as_remote_mut() {
1245 worktree.disconnected_from_host();
1246 }
1247 });
1248 }
1249 }
1250
1251 for open_buffer in self.opened_buffers.values_mut() {
1252 // Wake up any tasks waiting for peers' edits to this buffer.
1253 if let Some(buffer) = open_buffer.upgrade(cx) {
1254 buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1255 }
1256
1257 if let OpenBuffer::Strong(buffer) = open_buffer {
1258 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1259 }
1260 }
1261
1262 // Wake up all futures currently waiting on a buffer to get opened,
1263 // to give them a chance to fail now that we've disconnected.
1264 *self.opened_buffer.0.borrow_mut() = ();
1265 }
1266 }
1267
1268 pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1269 cx.emit(Event::Closed);
1270 }
1271
1272 pub fn is_read_only(&self) -> bool {
1273 match &self.client_state {
1274 Some(ProjectClientState::Remote {
1275 sharing_has_stopped,
1276 ..
1277 }) => *sharing_has_stopped,
1278 _ => false,
1279 }
1280 }
1281
1282 pub fn is_local(&self) -> bool {
1283 match &self.client_state {
1284 Some(ProjectClientState::Remote { .. }) => false,
1285 _ => true,
1286 }
1287 }
1288
1289 pub fn is_remote(&self) -> bool {
1290 !self.is_local()
1291 }
1292
1293 pub fn create_buffer(
1294 &mut self,
1295 text: &str,
1296 language: Option<Arc<Language>>,
1297 cx: &mut ModelContext<Self>,
1298 ) -> Result<ModelHandle<Buffer>> {
1299 if self.is_remote() {
1300 return Err(anyhow!("creating buffers as a guest is not supported yet"));
1301 }
1302
1303 let buffer = cx.add_model(|cx| {
1304 Buffer::new(self.replica_id(), text, cx)
1305 .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1306 });
1307 self.register_buffer(&buffer, cx)?;
1308 Ok(buffer)
1309 }
1310
1311 pub fn open_path(
1312 &mut self,
1313 path: impl Into<ProjectPath>,
1314 cx: &mut ModelContext<Self>,
1315 ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1316 let task = self.open_buffer(path, cx);
1317 cx.spawn_weak(|_, cx| async move {
1318 let buffer = task.await?;
1319 let project_entry_id = buffer
1320 .read_with(&cx, |buffer, cx| {
1321 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1322 })
1323 .ok_or_else(|| anyhow!("no project entry"))?;
1324
1325 let buffer: &AnyModelHandle = &buffer;
1326 Ok((project_entry_id, buffer.clone()))
1327 })
1328 }
1329
1330 pub fn open_local_buffer(
1331 &mut self,
1332 abs_path: impl AsRef<Path>,
1333 cx: &mut ModelContext<Self>,
1334 ) -> Task<Result<ModelHandle<Buffer>>> {
1335 if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1336 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1337 } else {
1338 Task::ready(Err(anyhow!("no such path")))
1339 }
1340 }
1341
1342 pub fn open_buffer(
1343 &mut self,
1344 path: impl Into<ProjectPath>,
1345 cx: &mut ModelContext<Self>,
1346 ) -> Task<Result<ModelHandle<Buffer>>> {
1347 let project_path = path.into();
1348 let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1349 worktree
1350 } else {
1351 return Task::ready(Err(anyhow!("no such worktree")));
1352 };
1353
1354 // If there is already a buffer for the given path, then return it.
1355 let existing_buffer = self.get_open_buffer(&project_path, cx);
1356 if let Some(existing_buffer) = existing_buffer {
1357 return Task::ready(Ok(existing_buffer));
1358 }
1359
1360 let mut loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
1361 // If the given path is already being loaded, then wait for that existing
1362 // task to complete and return the same buffer.
1363 hash_map::Entry::Occupied(e) => e.get().clone(),
1364
1365 // Otherwise, record the fact that this path is now being loaded.
1366 hash_map::Entry::Vacant(entry) => {
1367 let (mut tx, rx) = postage::watch::channel();
1368 entry.insert(rx.clone());
1369
1370 let load_buffer = if worktree.read(cx).is_local() {
1371 self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1372 } else {
1373 self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1374 };
1375
1376 cx.spawn(move |this, mut cx| async move {
1377 let load_result = load_buffer.await;
1378 *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1379 // Record the fact that the buffer is no longer loading.
1380 this.loading_buffers_by_path.remove(&project_path);
1381 let buffer = load_result.map_err(Arc::new)?;
1382 Ok(buffer)
1383 }));
1384 })
1385 .detach();
1386 rx
1387 }
1388 };
1389
1390 cx.foreground().spawn(async move {
1391 loop {
1392 if let Some(result) = loading_watch.borrow().as_ref() {
1393 match result {
1394 Ok(buffer) => return Ok(buffer.clone()),
1395 Err(error) => return Err(anyhow!("{}", error)),
1396 }
1397 }
1398 loading_watch.next().await;
1399 }
1400 })
1401 }
1402
1403 fn open_local_buffer_internal(
1404 &mut self,
1405 path: &Arc<Path>,
1406 worktree: &ModelHandle<Worktree>,
1407 cx: &mut ModelContext<Self>,
1408 ) -> Task<Result<ModelHandle<Buffer>>> {
1409 let load_buffer = worktree.update(cx, |worktree, cx| {
1410 let worktree = worktree.as_local_mut().unwrap();
1411 worktree.load_buffer(path, cx)
1412 });
1413 cx.spawn(|this, mut cx| async move {
1414 let buffer = load_buffer.await?;
1415 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1416 Ok(buffer)
1417 })
1418 }
1419
1420 fn open_remote_buffer_internal(
1421 &mut self,
1422 path: &Arc<Path>,
1423 worktree: &ModelHandle<Worktree>,
1424 cx: &mut ModelContext<Self>,
1425 ) -> Task<Result<ModelHandle<Buffer>>> {
1426 let rpc = self.client.clone();
1427 let project_id = self.remote_id().unwrap();
1428 let remote_worktree_id = worktree.read(cx).id();
1429 let path = path.clone();
1430 let path_string = path.to_string_lossy().to_string();
1431 cx.spawn(|this, mut cx| async move {
1432 let response = rpc
1433 .request(proto::OpenBufferByPath {
1434 project_id,
1435 worktree_id: remote_worktree_id.to_proto(),
1436 path: path_string,
1437 })
1438 .await?;
1439 this.update(&mut cx, |this, cx| {
1440 this.wait_for_remote_buffer(response.buffer_id, cx)
1441 })
1442 .await
1443 })
1444 }
1445
1446 /// LanguageServerName is owned, because it is inserted into a map
1447 fn open_local_buffer_via_lsp(
1448 &mut self,
1449 abs_path: lsp::Url,
1450 language_server_id: usize,
1451 language_server_name: LanguageServerName,
1452 cx: &mut ModelContext<Self>,
1453 ) -> Task<Result<ModelHandle<Buffer>>> {
1454 cx.spawn(|this, mut cx| async move {
1455 let abs_path = abs_path
1456 .to_file_path()
1457 .map_err(|_| anyhow!("can't convert URI to path"))?;
1458 let (worktree, relative_path) = if let Some(result) =
1459 this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1460 {
1461 result
1462 } else {
1463 let worktree = this
1464 .update(&mut cx, |this, cx| {
1465 this.create_local_worktree(&abs_path, false, cx)
1466 })
1467 .await?;
1468 this.update(&mut cx, |this, cx| {
1469 this.language_server_ids.insert(
1470 (worktree.read(cx).id(), language_server_name),
1471 language_server_id,
1472 );
1473 });
1474 (worktree, PathBuf::new())
1475 };
1476
1477 let project_path = ProjectPath {
1478 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1479 path: relative_path.into(),
1480 };
1481 this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1482 .await
1483 })
1484 }
1485
1486 pub fn open_buffer_by_id(
1487 &mut self,
1488 id: u64,
1489 cx: &mut ModelContext<Self>,
1490 ) -> Task<Result<ModelHandle<Buffer>>> {
1491 if let Some(buffer) = self.buffer_for_id(id, cx) {
1492 Task::ready(Ok(buffer))
1493 } else if self.is_local() {
1494 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1495 } else if let Some(project_id) = self.remote_id() {
1496 let request = self
1497 .client
1498 .request(proto::OpenBufferById { project_id, id });
1499 cx.spawn(|this, mut cx| async move {
1500 let buffer_id = request.await?.buffer_id;
1501 this.update(&mut cx, |this, cx| {
1502 this.wait_for_remote_buffer(buffer_id, cx)
1503 })
1504 .await
1505 })
1506 } else {
1507 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1508 }
1509 }
1510
1511 pub fn save_buffers(
1512 &self,
1513 buffers: HashSet<ModelHandle<Buffer>>,
1514 cx: &mut ModelContext<Self>,
1515 ) -> Task<Result<()>> {
1516 cx.spawn(|this, mut cx| async move {
1517 let save_tasks = buffers
1518 .into_iter()
1519 .map(|buffer| this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx)));
1520 try_join_all(save_tasks).await?;
1521 Ok(())
1522 })
1523 }
1524
1525 pub fn save_buffer(
1526 &self,
1527 buffer: ModelHandle<Buffer>,
1528 cx: &mut ModelContext<Self>,
1529 ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
1530 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1531 return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1532 };
1533 let worktree = file.worktree.clone();
1534 let path = file.path.clone();
1535 worktree.update(cx, |worktree, cx| match worktree {
1536 Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1537 Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1538 })
1539 }
1540
1541 pub fn save_buffer_as(
1542 &mut self,
1543 buffer: ModelHandle<Buffer>,
1544 abs_path: PathBuf,
1545 cx: &mut ModelContext<Self>,
1546 ) -> Task<Result<()>> {
1547 let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1548 let old_path =
1549 File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1550 cx.spawn(|this, mut cx| async move {
1551 if let Some(old_path) = old_path {
1552 this.update(&mut cx, |this, cx| {
1553 this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1554 });
1555 }
1556 let (worktree, path) = worktree_task.await?;
1557 worktree
1558 .update(&mut cx, |worktree, cx| match worktree {
1559 Worktree::Local(worktree) => {
1560 worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1561 }
1562 Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1563 })
1564 .await?;
1565 this.update(&mut cx, |this, cx| {
1566 this.detect_language_for_buffer(&buffer, cx);
1567 this.register_buffer_with_language_server(&buffer, cx);
1568 });
1569 Ok(())
1570 })
1571 }
1572
1573 pub fn get_open_buffer(
1574 &mut self,
1575 path: &ProjectPath,
1576 cx: &mut ModelContext<Self>,
1577 ) -> Option<ModelHandle<Buffer>> {
1578 let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1579 self.opened_buffers.values().find_map(|buffer| {
1580 let buffer = buffer.upgrade(cx)?;
1581 let file = File::from_dyn(buffer.read(cx).file())?;
1582 if file.worktree == worktree && file.path() == &path.path {
1583 Some(buffer)
1584 } else {
1585 None
1586 }
1587 })
1588 }
1589
1590 fn register_buffer(
1591 &mut self,
1592 buffer: &ModelHandle<Buffer>,
1593 cx: &mut ModelContext<Self>,
1594 ) -> Result<()> {
1595 buffer.update(cx, |buffer, _| {
1596 buffer.set_language_registry(self.languages.clone())
1597 });
1598
1599 let remote_id = buffer.read(cx).remote_id();
1600 let is_remote = self.is_remote();
1601 let open_buffer = if is_remote || self.is_shared() {
1602 OpenBuffer::Strong(buffer.clone())
1603 } else {
1604 OpenBuffer::Weak(buffer.downgrade())
1605 };
1606
1607 match self.opened_buffers.entry(remote_id) {
1608 hash_map::Entry::Vacant(entry) => {
1609 entry.insert(open_buffer);
1610 }
1611 hash_map::Entry::Occupied(mut entry) => {
1612 if let OpenBuffer::Operations(operations) = entry.get_mut() {
1613 buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
1614 } else if entry.get().upgrade(cx).is_some() {
1615 if is_remote {
1616 return Ok(());
1617 } else {
1618 debug_panic!("buffer {} was already registered", remote_id);
1619 Err(anyhow!("buffer {} was already registered", remote_id))?;
1620 }
1621 }
1622 entry.insert(open_buffer);
1623 }
1624 }
1625 cx.subscribe(buffer, |this, buffer, event, cx| {
1626 this.on_buffer_event(buffer, event, cx);
1627 })
1628 .detach();
1629
1630 self.detect_language_for_buffer(buffer, cx);
1631 self.register_buffer_with_language_server(buffer, cx);
1632 self.register_buffer_with_copilot(buffer, cx);
1633 cx.observe_release(buffer, |this, buffer, cx| {
1634 if let Some(file) = File::from_dyn(buffer.file()) {
1635 if file.is_local() {
1636 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1637 if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1638 server
1639 .notify::<lsp::notification::DidCloseTextDocument>(
1640 lsp::DidCloseTextDocumentParams {
1641 text_document: lsp::TextDocumentIdentifier::new(uri),
1642 },
1643 )
1644 .log_err();
1645 }
1646 }
1647 }
1648 })
1649 .detach();
1650
1651 *self.opened_buffer.0.borrow_mut() = ();
1652 Ok(())
1653 }
1654
1655 fn register_buffer_with_language_server(
1656 &mut self,
1657 buffer_handle: &ModelHandle<Buffer>,
1658 cx: &mut ModelContext<Self>,
1659 ) {
1660 let buffer = buffer_handle.read(cx);
1661 let buffer_id = buffer.remote_id();
1662 if let Some(file) = File::from_dyn(buffer.file()) {
1663 if file.is_local() {
1664 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1665 let initial_snapshot = buffer.text_snapshot();
1666
1667 let mut language_server = None;
1668 let mut language_id = None;
1669 if let Some(language) = buffer.language() {
1670 let worktree_id = file.worktree_id(cx);
1671 if let Some(adapter) = language.lsp_adapter() {
1672 language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
1673 language_server = self
1674 .language_server_ids
1675 .get(&(worktree_id, adapter.name.clone()))
1676 .and_then(|id| self.language_servers.get(id))
1677 .and_then(|server_state| {
1678 if let LanguageServerState::Running { server, .. } = server_state {
1679 Some(server.clone())
1680 } else {
1681 None
1682 }
1683 });
1684 }
1685 }
1686
1687 if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1688 if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1689 self.update_buffer_diagnostics(buffer_handle, diagnostics, None, cx)
1690 .log_err();
1691 }
1692 }
1693
1694 if let Some(server) = language_server {
1695 server
1696 .notify::<lsp::notification::DidOpenTextDocument>(
1697 lsp::DidOpenTextDocumentParams {
1698 text_document: lsp::TextDocumentItem::new(
1699 uri,
1700 language_id.unwrap_or_default(),
1701 0,
1702 initial_snapshot.text(),
1703 ),
1704 },
1705 )
1706 .log_err();
1707 buffer_handle.update(cx, |buffer, cx| {
1708 buffer.set_completion_triggers(
1709 server
1710 .capabilities()
1711 .completion_provider
1712 .as_ref()
1713 .and_then(|provider| provider.trigger_characters.clone())
1714 .unwrap_or_default(),
1715 cx,
1716 )
1717 });
1718 self.buffer_snapshots
1719 .insert(buffer_id, vec![(0, initial_snapshot)]);
1720 }
1721 }
1722 }
1723 }
1724
1725 fn unregister_buffer_from_language_server(
1726 &mut self,
1727 buffer: &ModelHandle<Buffer>,
1728 old_path: PathBuf,
1729 cx: &mut ModelContext<Self>,
1730 ) {
1731 buffer.update(cx, |buffer, cx| {
1732 buffer.update_diagnostics(Default::default(), cx);
1733 self.buffer_snapshots.remove(&buffer.remote_id());
1734 if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1735 language_server
1736 .notify::<lsp::notification::DidCloseTextDocument>(
1737 lsp::DidCloseTextDocumentParams {
1738 text_document: lsp::TextDocumentIdentifier::new(
1739 lsp::Url::from_file_path(old_path).unwrap(),
1740 ),
1741 },
1742 )
1743 .log_err();
1744 }
1745 });
1746 }
1747
1748 fn register_buffer_with_copilot(
1749 &self,
1750 buffer_handle: &ModelHandle<Buffer>,
1751 cx: &mut ModelContext<Self>,
1752 ) {
1753 if let Some(copilot) = Copilot::global(cx) {
1754 copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
1755 }
1756 }
1757
1758 async fn send_buffer_messages(
1759 this: WeakModelHandle<Self>,
1760 rx: UnboundedReceiver<BufferMessage>,
1761 mut cx: AsyncAppContext,
1762 ) -> Option<()> {
1763 const MAX_BATCH_SIZE: usize = 128;
1764
1765 let mut needs_resync_with_host = false;
1766 let mut operations_by_buffer_id = HashMap::default();
1767 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
1768 while let Some(changes) = changes.next().await {
1769 let this = this.upgrade(&mut cx)?;
1770 let is_local = this.read_with(&cx, |this, _| this.is_local());
1771
1772 for change in changes {
1773 match change {
1774 BufferMessage::Operation {
1775 buffer_id,
1776 operation,
1777 } => {
1778 if needs_resync_with_host {
1779 continue;
1780 }
1781
1782 operations_by_buffer_id
1783 .entry(buffer_id)
1784 .or_insert(Vec::new())
1785 .push(operation);
1786 }
1787 BufferMessage::Resync => {
1788 operations_by_buffer_id.clear();
1789 if this
1790 .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))
1791 .await
1792 .is_ok()
1793 {
1794 needs_resync_with_host = false;
1795 }
1796 }
1797 }
1798 }
1799
1800 for (buffer_id, operations) in operations_by_buffer_id.drain() {
1801 let request = this.read_with(&cx, |this, _| {
1802 let project_id = this.remote_id()?;
1803 Some(this.client.request(proto::UpdateBuffer {
1804 buffer_id,
1805 project_id,
1806 operations,
1807 }))
1808 });
1809 if let Some(request) = request {
1810 if request.await.is_err() && !is_local {
1811 needs_resync_with_host = true;
1812 break;
1813 }
1814 }
1815 }
1816 }
1817
1818 None
1819 }
1820
1821 fn on_buffer_event(
1822 &mut self,
1823 buffer: ModelHandle<Buffer>,
1824 event: &BufferEvent,
1825 cx: &mut ModelContext<Self>,
1826 ) -> Option<()> {
1827 match event {
1828 BufferEvent::Operation(operation) => {
1829 self.buffer_changes_tx
1830 .unbounded_send(BufferMessage::Operation {
1831 buffer_id: buffer.read(cx).remote_id(),
1832 operation: language::proto::serialize_operation(operation),
1833 })
1834 .ok();
1835 }
1836 BufferEvent::Edited { .. } => {
1837 let language_server = self
1838 .language_server_for_buffer(buffer.read(cx), cx)
1839 .map(|(_, server)| server.clone())?;
1840 let buffer = buffer.read(cx);
1841 let file = File::from_dyn(buffer.file())?;
1842 let abs_path = file.as_local()?.abs_path(cx);
1843 let uri = lsp::Url::from_file_path(abs_path).unwrap();
1844 let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1845 let (version, prev_snapshot) = buffer_snapshots.last()?;
1846 let next_snapshot = buffer.text_snapshot();
1847 let next_version = version + 1;
1848
1849 let content_changes = buffer
1850 .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1851 .map(|edit| {
1852 let edit_start = edit.new.start.0;
1853 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1854 let new_text = next_snapshot
1855 .text_for_range(edit.new.start.1..edit.new.end.1)
1856 .collect();
1857 lsp::TextDocumentContentChangeEvent {
1858 range: Some(lsp::Range::new(
1859 point_to_lsp(edit_start),
1860 point_to_lsp(edit_end),
1861 )),
1862 range_length: None,
1863 text: new_text,
1864 }
1865 })
1866 .collect();
1867
1868 buffer_snapshots.push((next_version, next_snapshot));
1869
1870 language_server
1871 .notify::<lsp::notification::DidChangeTextDocument>(
1872 lsp::DidChangeTextDocumentParams {
1873 text_document: lsp::VersionedTextDocumentIdentifier::new(
1874 uri,
1875 next_version,
1876 ),
1877 content_changes,
1878 },
1879 )
1880 .log_err();
1881 }
1882 BufferEvent::Saved => {
1883 let file = File::from_dyn(buffer.read(cx).file())?;
1884 let worktree_id = file.worktree_id(cx);
1885 let abs_path = file.as_local()?.abs_path(cx);
1886 let text_document = lsp::TextDocumentIdentifier {
1887 uri: lsp::Url::from_file_path(abs_path).unwrap(),
1888 };
1889
1890 for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
1891 server
1892 .notify::<lsp::notification::DidSaveTextDocument>(
1893 lsp::DidSaveTextDocumentParams {
1894 text_document: text_document.clone(),
1895 text: None,
1896 },
1897 )
1898 .log_err();
1899 }
1900
1901 let language_server_id = self.language_server_id_for_buffer(buffer.read(cx), cx)?;
1902 if let Some(LanguageServerState::Running {
1903 adapter,
1904 simulate_disk_based_diagnostics_completion,
1905 ..
1906 }) = self.language_servers.get_mut(&language_server_id)
1907 {
1908 // After saving a buffer using a language server that doesn't provide
1909 // a disk-based progress token, kick off a timer that will reset every
1910 // time the buffer is saved. If the timer eventually fires, simulate
1911 // disk-based diagnostics being finished so that other pieces of UI
1912 // (e.g., project diagnostics view, diagnostic status bar) can update.
1913 // We don't emit an event right away because the language server might take
1914 // some time to publish diagnostics.
1915 if adapter.disk_based_diagnostics_progress_token.is_none() {
1916 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
1917
1918 let task = cx.spawn_weak(|this, mut cx| async move {
1919 cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
1920 if let Some(this) = this.upgrade(&cx) {
1921 this.update(&mut cx, |this, cx | {
1922 this.disk_based_diagnostics_finished(language_server_id, cx);
1923 this.broadcast_language_server_update(
1924 language_server_id,
1925 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1926 proto::LspDiskBasedDiagnosticsUpdated {},
1927 ),
1928 );
1929 });
1930 }
1931 });
1932 *simulate_disk_based_diagnostics_completion = Some(task);
1933 }
1934 }
1935 }
1936 _ => {}
1937 }
1938
1939 None
1940 }
1941
1942 fn language_servers_for_worktree(
1943 &self,
1944 worktree_id: WorktreeId,
1945 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
1946 self.language_server_ids
1947 .iter()
1948 .filter_map(move |((language_server_worktree_id, _), id)| {
1949 if *language_server_worktree_id == worktree_id {
1950 if let Some(LanguageServerState::Running {
1951 adapter,
1952 language,
1953 server,
1954 ..
1955 }) = self.language_servers.get(id)
1956 {
1957 return Some((adapter, language, server));
1958 }
1959 }
1960 None
1961 })
1962 }
1963
1964 fn maintain_buffer_languages(
1965 languages: &LanguageRegistry,
1966 cx: &mut ModelContext<Project>,
1967 ) -> Task<()> {
1968 let mut subscription = languages.subscribe();
1969 cx.spawn_weak(|project, mut cx| async move {
1970 while let Some(()) = subscription.next().await {
1971 if let Some(project) = project.upgrade(&cx) {
1972 project.update(&mut cx, |project, cx| {
1973 let mut plain_text_buffers = Vec::new();
1974 let mut buffers_with_unknown_injections = Vec::new();
1975 for buffer in project.opened_buffers.values() {
1976 if let Some(handle) = buffer.upgrade(cx) {
1977 let buffer = &handle.read(cx);
1978 if buffer.language().is_none()
1979 || buffer.language() == Some(&*language::PLAIN_TEXT)
1980 {
1981 plain_text_buffers.push(handle);
1982 } else if buffer.contains_unknown_injections() {
1983 buffers_with_unknown_injections.push(handle);
1984 }
1985 }
1986 }
1987
1988 for buffer in plain_text_buffers {
1989 project.detect_language_for_buffer(&buffer, cx);
1990 project.register_buffer_with_language_server(&buffer, cx);
1991 }
1992
1993 for buffer in buffers_with_unknown_injections {
1994 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
1995 }
1996 });
1997 }
1998 }
1999 })
2000 }
2001
2002 fn maintain_workspace_config(
2003 languages: Arc<LanguageRegistry>,
2004 cx: &mut ModelContext<Project>,
2005 ) -> Task<()> {
2006 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2007 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2008
2009 let settings_observation = cx.observe_global::<Settings, _>(move |_, _| {
2010 *settings_changed_tx.borrow_mut() = ();
2011 });
2012 cx.spawn_weak(|this, mut cx| async move {
2013 while let Some(_) = settings_changed_rx.next().await {
2014 let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2015 if let Some(this) = this.upgrade(&cx) {
2016 this.read_with(&cx, |this, _| {
2017 for server_state in this.language_servers.values() {
2018 if let LanguageServerState::Running { server, .. } = server_state {
2019 server
2020 .notify::<lsp::notification::DidChangeConfiguration>(
2021 lsp::DidChangeConfigurationParams {
2022 settings: workspace_config.clone(),
2023 },
2024 )
2025 .ok();
2026 }
2027 }
2028 })
2029 } else {
2030 break;
2031 }
2032 }
2033
2034 drop(settings_observation);
2035 })
2036 }
2037
2038 fn detect_language_for_buffer(
2039 &mut self,
2040 buffer_handle: &ModelHandle<Buffer>,
2041 cx: &mut ModelContext<Self>,
2042 ) -> Option<()> {
2043 // If the buffer has a language, set it and start the language server if we haven't already.
2044 let buffer = buffer_handle.read(cx);
2045 let full_path = buffer.file()?.full_path(cx);
2046 let content = buffer.as_rope();
2047 let new_language = self
2048 .languages
2049 .language_for_file(&full_path, Some(content))
2050 .now_or_never()?
2051 .ok()?;
2052 self.set_language_for_buffer(buffer_handle, new_language, cx);
2053 None
2054 }
2055
2056 pub fn set_language_for_buffer(
2057 &mut self,
2058 buffer: &ModelHandle<Buffer>,
2059 new_language: Arc<Language>,
2060 cx: &mut ModelContext<Self>,
2061 ) {
2062 buffer.update(cx, |buffer, cx| {
2063 if buffer.language().map_or(true, |old_language| {
2064 !Arc::ptr_eq(old_language, &new_language)
2065 }) {
2066 buffer.set_language(Some(new_language.clone()), cx);
2067 }
2068 });
2069
2070 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
2071 if let Some(worktree) = file.worktree.read(cx).as_local() {
2072 let worktree_id = worktree.id();
2073 let worktree_abs_path = worktree.abs_path().clone();
2074 self.start_language_server(worktree_id, worktree_abs_path, new_language, cx);
2075 }
2076 }
2077 }
2078
2079 fn start_language_server(
2080 &mut self,
2081 worktree_id: WorktreeId,
2082 worktree_path: Arc<Path>,
2083 language: Arc<Language>,
2084 cx: &mut ModelContext<Self>,
2085 ) {
2086 if !cx
2087 .global::<Settings>()
2088 .enable_language_server(Some(&language.name()))
2089 {
2090 return;
2091 }
2092
2093 let adapter = if let Some(adapter) = language.lsp_adapter() {
2094 adapter
2095 } else {
2096 return;
2097 };
2098 let key = (worktree_id, adapter.name.clone());
2099
2100 let mut initialization_options = adapter.initialization_options.clone();
2101
2102 let lsp = &cx.global::<Settings>().lsp.get(&adapter.name.0);
2103 let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2104 match (&mut initialization_options, override_options) {
2105 (Some(initialization_options), Some(override_options)) => {
2106 merge_json_value_into(override_options, initialization_options);
2107 }
2108 (None, override_options) => initialization_options = override_options,
2109 _ => {}
2110 }
2111
2112 self.language_server_ids
2113 .entry(key.clone())
2114 .or_insert_with(|| {
2115 let languages = self.languages.clone();
2116 let server_id = post_inc(&mut self.next_language_server_id);
2117 let language_server = self.languages.start_language_server(
2118 server_id,
2119 language.clone(),
2120 worktree_path,
2121 self.client.http_client(),
2122 cx,
2123 );
2124 self.language_servers.insert(
2125 server_id,
2126 LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
2127 let workspace_config =
2128 cx.update(|cx| languages.workspace_configuration(cx)).await;
2129 let language_server = language_server?.await.log_err()?;
2130 let language_server = language_server
2131 .initialize(initialization_options)
2132 .await
2133 .log_err()?;
2134 let this = this.upgrade(&cx)?;
2135
2136 language_server
2137 .on_notification::<lsp::notification::PublishDiagnostics, _>({
2138 let this = this.downgrade();
2139 let adapter = adapter.clone();
2140 move |mut params, cx| {
2141 let this = this;
2142 let adapter = adapter.clone();
2143 cx.spawn(|mut cx| async move {
2144 adapter.process_diagnostics(&mut params).await;
2145 if let Some(this) = this.upgrade(&cx) {
2146 this.update(&mut cx, |this, cx| {
2147 this.update_diagnostics(
2148 server_id,
2149 params,
2150 &adapter.disk_based_diagnostic_sources,
2151 cx,
2152 )
2153 .log_err();
2154 });
2155 }
2156 })
2157 .detach();
2158 }
2159 })
2160 .detach();
2161
2162 language_server
2163 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2164 let languages = languages.clone();
2165 move |params, mut cx| {
2166 let languages = languages.clone();
2167 async move {
2168 let workspace_config = cx
2169 .update(|cx| languages.workspace_configuration(cx))
2170 .await;
2171 Ok(params
2172 .items
2173 .into_iter()
2174 .map(|item| {
2175 if let Some(section) = &item.section {
2176 workspace_config
2177 .get(section)
2178 .cloned()
2179 .unwrap_or(serde_json::Value::Null)
2180 } else {
2181 workspace_config.clone()
2182 }
2183 })
2184 .collect())
2185 }
2186 }
2187 })
2188 .detach();
2189
2190 // Even though we don't have handling for these requests, respond to them to
2191 // avoid stalling any language server like `gopls` which waits for a response
2192 // to these requests when initializing.
2193 language_server
2194 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2195 let this = this.downgrade();
2196 move |params, mut cx| async move {
2197 if let Some(this) = this.upgrade(&cx) {
2198 this.update(&mut cx, |this, _| {
2199 if let Some(status) =
2200 this.language_server_statuses.get_mut(&server_id)
2201 {
2202 if let lsp::NumberOrString::String(token) =
2203 params.token
2204 {
2205 status.progress_tokens.insert(token);
2206 }
2207 }
2208 });
2209 }
2210 Ok(())
2211 }
2212 })
2213 .detach();
2214 language_server
2215 .on_request::<lsp::request::RegisterCapability, _, _>({
2216 let this = this.downgrade();
2217 move |params, mut cx| async move {
2218 let this = this
2219 .upgrade(&cx)
2220 .ok_or_else(|| anyhow!("project dropped"))?;
2221 for reg in params.registrations {
2222 if reg.method == "workspace/didChangeWatchedFiles" {
2223 if let Some(options) = reg.register_options {
2224 let options = serde_json::from_value(options)?;
2225 this.update(&mut cx, |this, cx| {
2226 this.on_lsp_did_change_watched_files(
2227 server_id, options, cx,
2228 );
2229 });
2230 }
2231 }
2232 }
2233 Ok(())
2234 }
2235 })
2236 .detach();
2237
2238 language_server
2239 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2240 let this = this.downgrade();
2241 let adapter = adapter.clone();
2242 let language_server = language_server.clone();
2243 move |params, cx| {
2244 Self::on_lsp_workspace_edit(
2245 this,
2246 params,
2247 server_id,
2248 adapter.clone(),
2249 language_server.clone(),
2250 cx,
2251 )
2252 }
2253 })
2254 .detach();
2255
2256 let disk_based_diagnostics_progress_token =
2257 adapter.disk_based_diagnostics_progress_token.clone();
2258
2259 language_server
2260 .on_notification::<lsp::notification::Progress, _>({
2261 let this = this.downgrade();
2262 move |params, mut cx| {
2263 if let Some(this) = this.upgrade(&cx) {
2264 this.update(&mut cx, |this, cx| {
2265 this.on_lsp_progress(
2266 params,
2267 server_id,
2268 disk_based_diagnostics_progress_token.clone(),
2269 cx,
2270 );
2271 });
2272 }
2273 }
2274 })
2275 .detach();
2276
2277 language_server
2278 .notify::<lsp::notification::DidChangeConfiguration>(
2279 lsp::DidChangeConfigurationParams {
2280 settings: workspace_config,
2281 },
2282 )
2283 .ok();
2284
2285 this.update(&mut cx, |this, cx| {
2286 // If the language server for this key doesn't match the server id, don't store the
2287 // server. Which will cause it to be dropped, killing the process
2288 if this
2289 .language_server_ids
2290 .get(&key)
2291 .map(|id| id != &server_id)
2292 .unwrap_or(false)
2293 {
2294 return None;
2295 }
2296
2297 // Update language_servers collection with Running variant of LanguageServerState
2298 // indicating that the server is up and running and ready
2299 this.language_servers.insert(
2300 server_id,
2301 LanguageServerState::Running {
2302 adapter: adapter.clone(),
2303 language,
2304 watched_paths: Default::default(),
2305 server: language_server.clone(),
2306 simulate_disk_based_diagnostics_completion: None,
2307 },
2308 );
2309 this.language_server_statuses.insert(
2310 server_id,
2311 LanguageServerStatus {
2312 name: language_server.name().to_string(),
2313 pending_work: Default::default(),
2314 has_pending_diagnostic_updates: false,
2315 progress_tokens: Default::default(),
2316 },
2317 );
2318
2319 if let Some(project_id) = this.remote_id() {
2320 this.client
2321 .send(proto::StartLanguageServer {
2322 project_id,
2323 server: Some(proto::LanguageServer {
2324 id: server_id as u64,
2325 name: language_server.name().to_string(),
2326 }),
2327 })
2328 .log_err();
2329 }
2330
2331 // Tell the language server about every open buffer in the worktree that matches the language.
2332 for buffer in this.opened_buffers.values() {
2333 if let Some(buffer_handle) = buffer.upgrade(cx) {
2334 let buffer = buffer_handle.read(cx);
2335 let file = if let Some(file) = File::from_dyn(buffer.file()) {
2336 file
2337 } else {
2338 continue;
2339 };
2340 let language = if let Some(language) = buffer.language() {
2341 language
2342 } else {
2343 continue;
2344 };
2345 if file.worktree.read(cx).id() != key.0
2346 || language.lsp_adapter().map(|a| a.name.clone())
2347 != Some(key.1.clone())
2348 {
2349 continue;
2350 }
2351
2352 let file = file.as_local()?;
2353 let versions = this
2354 .buffer_snapshots
2355 .entry(buffer.remote_id())
2356 .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2357
2358 let (version, initial_snapshot) = versions.last().unwrap();
2359 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2360 language_server
2361 .notify::<lsp::notification::DidOpenTextDocument>(
2362 lsp::DidOpenTextDocumentParams {
2363 text_document: lsp::TextDocumentItem::new(
2364 uri,
2365 adapter
2366 .language_ids
2367 .get(language.name().as_ref())
2368 .cloned()
2369 .unwrap_or_default(),
2370 *version,
2371 initial_snapshot.text(),
2372 ),
2373 },
2374 )
2375 .log_err()?;
2376 buffer_handle.update(cx, |buffer, cx| {
2377 buffer.set_completion_triggers(
2378 language_server
2379 .capabilities()
2380 .completion_provider
2381 .as_ref()
2382 .and_then(|provider| {
2383 provider.trigger_characters.clone()
2384 })
2385 .unwrap_or_default(),
2386 cx,
2387 )
2388 });
2389 }
2390 }
2391
2392 cx.notify();
2393 Some(language_server)
2394 })
2395 })),
2396 );
2397
2398 server_id
2399 });
2400 }
2401
2402 // Returns a list of all of the worktrees which no longer have a language server and the root path
2403 // for the stopped server
2404 fn stop_language_server(
2405 &mut self,
2406 worktree_id: WorktreeId,
2407 adapter_name: LanguageServerName,
2408 cx: &mut ModelContext<Self>,
2409 ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2410 let key = (worktree_id, adapter_name);
2411 if let Some(server_id) = self.language_server_ids.remove(&key) {
2412 // Remove other entries for this language server as well
2413 let mut orphaned_worktrees = vec![worktree_id];
2414 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2415 for other_key in other_keys {
2416 if self.language_server_ids.get(&other_key) == Some(&server_id) {
2417 self.language_server_ids.remove(&other_key);
2418 orphaned_worktrees.push(other_key.0);
2419 }
2420 }
2421
2422 self.language_server_statuses.remove(&server_id);
2423 cx.notify();
2424
2425 let server_state = self.language_servers.remove(&server_id);
2426 cx.spawn_weak(|this, mut cx| async move {
2427 let mut root_path = None;
2428
2429 let server = match server_state {
2430 Some(LanguageServerState::Starting(started_language_server)) => {
2431 started_language_server.await
2432 }
2433 Some(LanguageServerState::Running { server, .. }) => Some(server),
2434 None => None,
2435 };
2436
2437 if let Some(server) = server {
2438 root_path = Some(server.root_path().clone());
2439 if let Some(shutdown) = server.shutdown() {
2440 shutdown.await;
2441 }
2442 }
2443
2444 if let Some(this) = this.upgrade(&cx) {
2445 this.update(&mut cx, |this, cx| {
2446 this.language_server_statuses.remove(&server_id);
2447 cx.notify();
2448 });
2449 }
2450
2451 (root_path, orphaned_worktrees)
2452 })
2453 } else {
2454 Task::ready((None, Vec::new()))
2455 }
2456 }
2457
2458 pub fn restart_language_servers_for_buffers(
2459 &mut self,
2460 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2461 cx: &mut ModelContext<Self>,
2462 ) -> Option<()> {
2463 let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, Arc<Language>)> = buffers
2464 .into_iter()
2465 .filter_map(|buffer| {
2466 let buffer = buffer.read(cx);
2467 let file = File::from_dyn(buffer.file())?;
2468 let worktree = file.worktree.read(cx).as_local()?;
2469 let full_path = file.full_path(cx);
2470 let language = self
2471 .languages
2472 .language_for_file(&full_path, Some(buffer.as_rope()))
2473 .now_or_never()?
2474 .ok()?;
2475 Some((worktree.id(), worktree.abs_path().clone(), language))
2476 })
2477 .collect();
2478 for (worktree_id, worktree_abs_path, language) in language_server_lookup_info {
2479 self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2480 }
2481
2482 None
2483 }
2484
2485 fn restart_language_server(
2486 &mut self,
2487 worktree_id: WorktreeId,
2488 fallback_path: Arc<Path>,
2489 language: Arc<Language>,
2490 cx: &mut ModelContext<Self>,
2491 ) {
2492 let adapter = if let Some(adapter) = language.lsp_adapter() {
2493 adapter
2494 } else {
2495 return;
2496 };
2497
2498 let server_name = adapter.name.clone();
2499 let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2500 cx.spawn_weak(|this, mut cx| async move {
2501 let (original_root_path, orphaned_worktrees) = stop.await;
2502 if let Some(this) = this.upgrade(&cx) {
2503 this.update(&mut cx, |this, cx| {
2504 // Attempt to restart using original server path. Fallback to passed in
2505 // path if we could not retrieve the root path
2506 let root_path = original_root_path
2507 .map(|path_buf| Arc::from(path_buf.as_path()))
2508 .unwrap_or(fallback_path);
2509
2510 this.start_language_server(worktree_id, root_path, language, cx);
2511
2512 // Lookup new server id and set it for each of the orphaned worktrees
2513 if let Some(new_server_id) = this
2514 .language_server_ids
2515 .get(&(worktree_id, server_name.clone()))
2516 .cloned()
2517 {
2518 for orphaned_worktree in orphaned_worktrees {
2519 this.language_server_ids
2520 .insert((orphaned_worktree, server_name.clone()), new_server_id);
2521 }
2522 }
2523 });
2524 }
2525 })
2526 .detach();
2527 }
2528
2529 fn on_lsp_progress(
2530 &mut self,
2531 progress: lsp::ProgressParams,
2532 server_id: usize,
2533 disk_based_diagnostics_progress_token: Option<String>,
2534 cx: &mut ModelContext<Self>,
2535 ) {
2536 let token = match progress.token {
2537 lsp::NumberOrString::String(token) => token,
2538 lsp::NumberOrString::Number(token) => {
2539 log::info!("skipping numeric progress token {}", token);
2540 return;
2541 }
2542 };
2543 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2544 let language_server_status =
2545 if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2546 status
2547 } else {
2548 return;
2549 };
2550
2551 if !language_server_status.progress_tokens.contains(&token) {
2552 return;
2553 }
2554
2555 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
2556 .as_ref()
2557 .map_or(false, |disk_based_token| {
2558 token.starts_with(disk_based_token)
2559 });
2560
2561 match progress {
2562 lsp::WorkDoneProgress::Begin(report) => {
2563 if is_disk_based_diagnostics_progress {
2564 language_server_status.has_pending_diagnostic_updates = true;
2565 self.disk_based_diagnostics_started(server_id, cx);
2566 self.broadcast_language_server_update(
2567 server_id,
2568 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2569 proto::LspDiskBasedDiagnosticsUpdating {},
2570 ),
2571 );
2572 } else {
2573 self.on_lsp_work_start(
2574 server_id,
2575 token.clone(),
2576 LanguageServerProgress {
2577 message: report.message.clone(),
2578 percentage: report.percentage.map(|p| p as usize),
2579 last_update_at: Instant::now(),
2580 },
2581 cx,
2582 );
2583 self.broadcast_language_server_update(
2584 server_id,
2585 proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2586 token,
2587 message: report.message,
2588 percentage: report.percentage.map(|p| p as u32),
2589 }),
2590 );
2591 }
2592 }
2593 lsp::WorkDoneProgress::Report(report) => {
2594 if !is_disk_based_diagnostics_progress {
2595 self.on_lsp_work_progress(
2596 server_id,
2597 token.clone(),
2598 LanguageServerProgress {
2599 message: report.message.clone(),
2600 percentage: report.percentage.map(|p| p as usize),
2601 last_update_at: Instant::now(),
2602 },
2603 cx,
2604 );
2605 self.broadcast_language_server_update(
2606 server_id,
2607 proto::update_language_server::Variant::WorkProgress(
2608 proto::LspWorkProgress {
2609 token,
2610 message: report.message,
2611 percentage: report.percentage.map(|p| p as u32),
2612 },
2613 ),
2614 );
2615 }
2616 }
2617 lsp::WorkDoneProgress::End(_) => {
2618 language_server_status.progress_tokens.remove(&token);
2619
2620 if is_disk_based_diagnostics_progress {
2621 language_server_status.has_pending_diagnostic_updates = false;
2622 self.disk_based_diagnostics_finished(server_id, cx);
2623 self.broadcast_language_server_update(
2624 server_id,
2625 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2626 proto::LspDiskBasedDiagnosticsUpdated {},
2627 ),
2628 );
2629 } else {
2630 self.on_lsp_work_end(server_id, token.clone(), cx);
2631 self.broadcast_language_server_update(
2632 server_id,
2633 proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2634 token,
2635 }),
2636 );
2637 }
2638 }
2639 }
2640 }
2641
2642 fn on_lsp_work_start(
2643 &mut self,
2644 language_server_id: usize,
2645 token: String,
2646 progress: LanguageServerProgress,
2647 cx: &mut ModelContext<Self>,
2648 ) {
2649 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2650 status.pending_work.insert(token, progress);
2651 cx.notify();
2652 }
2653 }
2654
2655 fn on_lsp_work_progress(
2656 &mut self,
2657 language_server_id: usize,
2658 token: String,
2659 progress: LanguageServerProgress,
2660 cx: &mut ModelContext<Self>,
2661 ) {
2662 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2663 let entry = status
2664 .pending_work
2665 .entry(token)
2666 .or_insert(LanguageServerProgress {
2667 message: Default::default(),
2668 percentage: Default::default(),
2669 last_update_at: progress.last_update_at,
2670 });
2671 if progress.message.is_some() {
2672 entry.message = progress.message;
2673 }
2674 if progress.percentage.is_some() {
2675 entry.percentage = progress.percentage;
2676 }
2677 entry.last_update_at = progress.last_update_at;
2678 cx.notify();
2679 }
2680 }
2681
2682 fn on_lsp_work_end(
2683 &mut self,
2684 language_server_id: usize,
2685 token: String,
2686 cx: &mut ModelContext<Self>,
2687 ) {
2688 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2689 status.pending_work.remove(&token);
2690 cx.notify();
2691 }
2692 }
2693
2694 fn on_lsp_did_change_watched_files(
2695 &mut self,
2696 language_server_id: usize,
2697 params: DidChangeWatchedFilesRegistrationOptions,
2698 cx: &mut ModelContext<Self>,
2699 ) {
2700 if let Some(LanguageServerState::Running { watched_paths, .. }) =
2701 self.language_servers.get_mut(&language_server_id)
2702 {
2703 watched_paths.clear();
2704 for watcher in params.watchers {
2705 watched_paths.add_pattern(&watcher.glob_pattern).log_err();
2706 }
2707 cx.notify();
2708 }
2709 }
2710
2711 async fn on_lsp_workspace_edit(
2712 this: WeakModelHandle<Self>,
2713 params: lsp::ApplyWorkspaceEditParams,
2714 server_id: usize,
2715 adapter: Arc<CachedLspAdapter>,
2716 language_server: Arc<LanguageServer>,
2717 mut cx: AsyncAppContext,
2718 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2719 let this = this
2720 .upgrade(&cx)
2721 .ok_or_else(|| anyhow!("project project closed"))?;
2722 let transaction = Self::deserialize_workspace_edit(
2723 this.clone(),
2724 params.edit,
2725 true,
2726 adapter.clone(),
2727 language_server.clone(),
2728 &mut cx,
2729 )
2730 .await
2731 .log_err();
2732 this.update(&mut cx, |this, _| {
2733 if let Some(transaction) = transaction {
2734 this.last_workspace_edits_by_language_server
2735 .insert(server_id, transaction);
2736 }
2737 });
2738 Ok(lsp::ApplyWorkspaceEditResponse {
2739 applied: true,
2740 failed_change: None,
2741 failure_reason: None,
2742 })
2743 }
2744
2745 fn broadcast_language_server_update(
2746 &self,
2747 language_server_id: usize,
2748 event: proto::update_language_server::Variant,
2749 ) {
2750 if let Some(project_id) = self.remote_id() {
2751 self.client
2752 .send(proto::UpdateLanguageServer {
2753 project_id,
2754 language_server_id: language_server_id as u64,
2755 variant: Some(event),
2756 })
2757 .log_err();
2758 }
2759 }
2760
2761 pub fn language_server_statuses(
2762 &self,
2763 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2764 self.language_server_statuses.values()
2765 }
2766
2767 pub fn update_diagnostics(
2768 &mut self,
2769 language_server_id: usize,
2770 mut params: lsp::PublishDiagnosticsParams,
2771 disk_based_sources: &[String],
2772 cx: &mut ModelContext<Self>,
2773 ) -> Result<()> {
2774 let abs_path = params
2775 .uri
2776 .to_file_path()
2777 .map_err(|_| anyhow!("URI is not a file"))?;
2778 let mut diagnostics = Vec::default();
2779 let mut primary_diagnostic_group_ids = HashMap::default();
2780 let mut sources_by_group_id = HashMap::default();
2781 let mut supporting_diagnostics = HashMap::default();
2782
2783 // Ensure that primary diagnostics are always the most severe
2784 params.diagnostics.sort_by_key(|item| item.severity);
2785
2786 for diagnostic in ¶ms.diagnostics {
2787 let source = diagnostic.source.as_ref();
2788 let code = diagnostic.code.as_ref().map(|code| match code {
2789 lsp::NumberOrString::Number(code) => code.to_string(),
2790 lsp::NumberOrString::String(code) => code.clone(),
2791 });
2792 let range = range_from_lsp(diagnostic.range);
2793 let is_supporting = diagnostic
2794 .related_information
2795 .as_ref()
2796 .map_or(false, |infos| {
2797 infos.iter().any(|info| {
2798 primary_diagnostic_group_ids.contains_key(&(
2799 source,
2800 code.clone(),
2801 range_from_lsp(info.location.range),
2802 ))
2803 })
2804 });
2805
2806 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2807 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2808 });
2809
2810 if is_supporting {
2811 supporting_diagnostics.insert(
2812 (source, code.clone(), range),
2813 (diagnostic.severity, is_unnecessary),
2814 );
2815 } else {
2816 let group_id = post_inc(&mut self.next_diagnostic_group_id);
2817 let is_disk_based =
2818 source.map_or(false, |source| disk_based_sources.contains(source));
2819
2820 sources_by_group_id.insert(group_id, source);
2821 primary_diagnostic_group_ids
2822 .insert((source, code.clone(), range.clone()), group_id);
2823
2824 diagnostics.push(DiagnosticEntry {
2825 range,
2826 diagnostic: Diagnostic {
2827 code: code.clone(),
2828 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2829 message: diagnostic.message.clone(),
2830 group_id,
2831 is_primary: true,
2832 is_valid: true,
2833 is_disk_based,
2834 is_unnecessary,
2835 },
2836 });
2837 if let Some(infos) = &diagnostic.related_information {
2838 for info in infos {
2839 if info.location.uri == params.uri && !info.message.is_empty() {
2840 let range = range_from_lsp(info.location.range);
2841 diagnostics.push(DiagnosticEntry {
2842 range,
2843 diagnostic: Diagnostic {
2844 code: code.clone(),
2845 severity: DiagnosticSeverity::INFORMATION,
2846 message: info.message.clone(),
2847 group_id,
2848 is_primary: false,
2849 is_valid: true,
2850 is_disk_based,
2851 is_unnecessary: false,
2852 },
2853 });
2854 }
2855 }
2856 }
2857 }
2858 }
2859
2860 for entry in &mut diagnostics {
2861 let diagnostic = &mut entry.diagnostic;
2862 if !diagnostic.is_primary {
2863 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2864 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2865 source,
2866 diagnostic.code.clone(),
2867 entry.range.clone(),
2868 )) {
2869 if let Some(severity) = severity {
2870 diagnostic.severity = severity;
2871 }
2872 diagnostic.is_unnecessary = is_unnecessary;
2873 }
2874 }
2875 }
2876
2877 self.update_diagnostic_entries(
2878 language_server_id,
2879 abs_path,
2880 params.version,
2881 diagnostics,
2882 cx,
2883 )?;
2884 Ok(())
2885 }
2886
2887 pub fn update_diagnostic_entries(
2888 &mut self,
2889 language_server_id: usize,
2890 abs_path: PathBuf,
2891 version: Option<i32>,
2892 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2893 cx: &mut ModelContext<Project>,
2894 ) -> Result<(), anyhow::Error> {
2895 let (worktree, relative_path) = self
2896 .find_local_worktree(&abs_path, cx)
2897 .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2898
2899 let project_path = ProjectPath {
2900 worktree_id: worktree.read(cx).id(),
2901 path: relative_path.into(),
2902 };
2903
2904 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2905 self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2906 }
2907
2908 let updated = worktree.update(cx, |worktree, cx| {
2909 worktree
2910 .as_local_mut()
2911 .ok_or_else(|| anyhow!("not a local worktree"))?
2912 .update_diagnostics(
2913 language_server_id,
2914 project_path.path.clone(),
2915 diagnostics,
2916 cx,
2917 )
2918 })?;
2919 if updated {
2920 cx.emit(Event::DiagnosticsUpdated {
2921 language_server_id,
2922 path: project_path,
2923 });
2924 }
2925 Ok(())
2926 }
2927
2928 fn update_buffer_diagnostics(
2929 &mut self,
2930 buffer: &ModelHandle<Buffer>,
2931 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2932 version: Option<i32>,
2933 cx: &mut ModelContext<Self>,
2934 ) -> Result<()> {
2935 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2936 Ordering::Equal
2937 .then_with(|| b.is_primary.cmp(&a.is_primary))
2938 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2939 .then_with(|| a.severity.cmp(&b.severity))
2940 .then_with(|| a.message.cmp(&b.message))
2941 }
2942
2943 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2944
2945 diagnostics.sort_unstable_by(|a, b| {
2946 Ordering::Equal
2947 .then_with(|| a.range.start.cmp(&b.range.start))
2948 .then_with(|| b.range.end.cmp(&a.range.end))
2949 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2950 });
2951
2952 let mut sanitized_diagnostics = Vec::new();
2953 let edits_since_save = Patch::new(
2954 snapshot
2955 .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
2956 .collect(),
2957 );
2958 for entry in diagnostics {
2959 let start;
2960 let end;
2961 if entry.diagnostic.is_disk_based {
2962 // Some diagnostics are based on files on disk instead of buffers'
2963 // current contents. Adjust these diagnostics' ranges to reflect
2964 // any unsaved edits.
2965 start = edits_since_save.old_to_new(entry.range.start);
2966 end = edits_since_save.old_to_new(entry.range.end);
2967 } else {
2968 start = entry.range.start;
2969 end = entry.range.end;
2970 }
2971
2972 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2973 ..snapshot.clip_point_utf16(end, Bias::Right);
2974
2975 // Expand empty ranges by one codepoint
2976 if range.start == range.end {
2977 // This will be go to the next boundary when being clipped
2978 range.end.column += 1;
2979 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
2980 if range.start == range.end && range.end.column > 0 {
2981 range.start.column -= 1;
2982 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
2983 }
2984 }
2985
2986 sanitized_diagnostics.push(DiagnosticEntry {
2987 range,
2988 diagnostic: entry.diagnostic,
2989 });
2990 }
2991 drop(edits_since_save);
2992
2993 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2994 buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2995 Ok(())
2996 }
2997
2998 pub fn reload_buffers(
2999 &self,
3000 buffers: HashSet<ModelHandle<Buffer>>,
3001 push_to_history: bool,
3002 cx: &mut ModelContext<Self>,
3003 ) -> Task<Result<ProjectTransaction>> {
3004 let mut local_buffers = Vec::new();
3005 let mut remote_buffers = None;
3006 for buffer_handle in buffers {
3007 let buffer = buffer_handle.read(cx);
3008 if buffer.is_dirty() {
3009 if let Some(file) = File::from_dyn(buffer.file()) {
3010 if file.is_local() {
3011 local_buffers.push(buffer_handle);
3012 } else {
3013 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3014 }
3015 }
3016 }
3017 }
3018
3019 let remote_buffers = self.remote_id().zip(remote_buffers);
3020 let client = self.client.clone();
3021
3022 cx.spawn(|this, mut cx| async move {
3023 let mut project_transaction = ProjectTransaction::default();
3024
3025 if let Some((project_id, remote_buffers)) = remote_buffers {
3026 let response = client
3027 .request(proto::ReloadBuffers {
3028 project_id,
3029 buffer_ids: remote_buffers
3030 .iter()
3031 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3032 .collect(),
3033 })
3034 .await?
3035 .transaction
3036 .ok_or_else(|| anyhow!("missing transaction"))?;
3037 project_transaction = this
3038 .update(&mut cx, |this, cx| {
3039 this.deserialize_project_transaction(response, push_to_history, cx)
3040 })
3041 .await?;
3042 }
3043
3044 for buffer in local_buffers {
3045 let transaction = buffer
3046 .update(&mut cx, |buffer, cx| buffer.reload(cx))
3047 .await?;
3048 buffer.update(&mut cx, |buffer, cx| {
3049 if let Some(transaction) = transaction {
3050 if !push_to_history {
3051 buffer.forget_transaction(transaction.id);
3052 }
3053 project_transaction.0.insert(cx.handle(), transaction);
3054 }
3055 });
3056 }
3057
3058 Ok(project_transaction)
3059 })
3060 }
3061
3062 pub fn format(
3063 &self,
3064 buffers: HashSet<ModelHandle<Buffer>>,
3065 push_to_history: bool,
3066 trigger: FormatTrigger,
3067 cx: &mut ModelContext<Project>,
3068 ) -> Task<Result<ProjectTransaction>> {
3069 if self.is_local() {
3070 let mut buffers_with_paths_and_servers = buffers
3071 .into_iter()
3072 .filter_map(|buffer_handle| {
3073 let buffer = buffer_handle.read(cx);
3074 let file = File::from_dyn(buffer.file())?;
3075 let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3076 let server = self
3077 .language_server_for_buffer(buffer, cx)
3078 .map(|s| s.1.clone());
3079 Some((buffer_handle, buffer_abs_path, server))
3080 })
3081 .collect::<Vec<_>>();
3082
3083 cx.spawn(|this, mut cx| async move {
3084 // Do not allow multiple concurrent formatting requests for the
3085 // same buffer.
3086 this.update(&mut cx, |this, _| {
3087 buffers_with_paths_and_servers
3088 .retain(|(buffer, _, _)| this.buffers_being_formatted.insert(buffer.id()));
3089 });
3090
3091 let _cleanup = defer({
3092 let this = this.clone();
3093 let mut cx = cx.clone();
3094 let buffers = &buffers_with_paths_and_servers;
3095 move || {
3096 this.update(&mut cx, |this, _| {
3097 for (buffer, _, _) in buffers {
3098 this.buffers_being_formatted.remove(&buffer.id());
3099 }
3100 });
3101 }
3102 });
3103
3104 let mut project_transaction = ProjectTransaction::default();
3105 for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
3106 let (
3107 format_on_save,
3108 remove_trailing_whitespace,
3109 ensure_final_newline,
3110 formatter,
3111 tab_size,
3112 ) = buffer.read_with(&cx, |buffer, cx| {
3113 let settings = cx.global::<Settings>();
3114 let language_name = buffer.language().map(|language| language.name());
3115 (
3116 settings.format_on_save(language_name.as_deref()),
3117 settings.remove_trailing_whitespace_on_save(language_name.as_deref()),
3118 settings.ensure_final_newline_on_save(language_name.as_deref()),
3119 settings.formatter(language_name.as_deref()),
3120 settings.tab_size(language_name.as_deref()),
3121 )
3122 });
3123
3124 // First, format buffer's whitespace according to the settings.
3125 let trailing_whitespace_diff = if remove_trailing_whitespace {
3126 Some(
3127 buffer
3128 .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
3129 .await,
3130 )
3131 } else {
3132 None
3133 };
3134 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
3135 buffer.finalize_last_transaction();
3136 buffer.start_transaction();
3137 if let Some(diff) = trailing_whitespace_diff {
3138 buffer.apply_diff(diff, cx);
3139 }
3140 if ensure_final_newline {
3141 buffer.ensure_final_newline(cx);
3142 }
3143 buffer.end_transaction(cx)
3144 });
3145
3146 // Currently, formatting operations are represented differently depending on
3147 // whether they come from a language server or an external command.
3148 enum FormatOperation {
3149 Lsp(Vec<(Range<Anchor>, String)>),
3150 External(Diff),
3151 }
3152
3153 // Apply language-specific formatting using either a language server
3154 // or external command.
3155 let mut format_operation = None;
3156 match (formatter, format_on_save) {
3157 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
3158
3159 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
3160 | (_, FormatOnSave::LanguageServer) => {
3161 if let Some((language_server, buffer_abs_path)) =
3162 language_server.as_ref().zip(buffer_abs_path.as_ref())
3163 {
3164 format_operation = Some(FormatOperation::Lsp(
3165 Self::format_via_lsp(
3166 &this,
3167 &buffer,
3168 buffer_abs_path,
3169 &language_server,
3170 tab_size,
3171 &mut cx,
3172 )
3173 .await
3174 .context("failed to format via language server")?,
3175 ));
3176 }
3177 }
3178
3179 (
3180 Formatter::External { command, arguments },
3181 FormatOnSave::On | FormatOnSave::Off,
3182 )
3183 | (_, FormatOnSave::External { command, arguments }) => {
3184 if let Some(buffer_abs_path) = buffer_abs_path {
3185 format_operation = Self::format_via_external_command(
3186 &buffer,
3187 &buffer_abs_path,
3188 &command,
3189 &arguments,
3190 &mut cx,
3191 )
3192 .await
3193 .context(format!(
3194 "failed to format via external command {:?}",
3195 command
3196 ))?
3197 .map(FormatOperation::External);
3198 }
3199 }
3200 };
3201
3202 buffer.update(&mut cx, |b, cx| {
3203 // If the buffer had its whitespace formatted and was edited while the language-specific
3204 // formatting was being computed, avoid applying the language-specific formatting, because
3205 // it can't be grouped with the whitespace formatting in the undo history.
3206 if let Some(transaction_id) = whitespace_transaction_id {
3207 if b.peek_undo_stack()
3208 .map_or(true, |e| e.transaction_id() != transaction_id)
3209 {
3210 format_operation.take();
3211 }
3212 }
3213
3214 // Apply any language-specific formatting, and group the two formatting operations
3215 // in the buffer's undo history.
3216 if let Some(operation) = format_operation {
3217 match operation {
3218 FormatOperation::Lsp(edits) => {
3219 b.edit(edits, None, cx);
3220 }
3221 FormatOperation::External(diff) => {
3222 b.apply_diff(diff, cx);
3223 }
3224 }
3225
3226 if let Some(transaction_id) = whitespace_transaction_id {
3227 b.group_until_transaction(transaction_id);
3228 }
3229 }
3230
3231 if let Some(transaction) = b.finalize_last_transaction().cloned() {
3232 if !push_to_history {
3233 b.forget_transaction(transaction.id);
3234 }
3235 project_transaction.0.insert(buffer.clone(), transaction);
3236 }
3237 });
3238 }
3239
3240 Ok(project_transaction)
3241 })
3242 } else {
3243 let remote_id = self.remote_id();
3244 let client = self.client.clone();
3245 cx.spawn(|this, mut cx| async move {
3246 let mut project_transaction = ProjectTransaction::default();
3247 if let Some(project_id) = remote_id {
3248 let response = client
3249 .request(proto::FormatBuffers {
3250 project_id,
3251 trigger: trigger as i32,
3252 buffer_ids: buffers
3253 .iter()
3254 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3255 .collect(),
3256 })
3257 .await?
3258 .transaction
3259 .ok_or_else(|| anyhow!("missing transaction"))?;
3260 project_transaction = this
3261 .update(&mut cx, |this, cx| {
3262 this.deserialize_project_transaction(response, push_to_history, cx)
3263 })
3264 .await?;
3265 }
3266 Ok(project_transaction)
3267 })
3268 }
3269 }
3270
3271 async fn format_via_lsp(
3272 this: &ModelHandle<Self>,
3273 buffer: &ModelHandle<Buffer>,
3274 abs_path: &Path,
3275 language_server: &Arc<LanguageServer>,
3276 tab_size: NonZeroU32,
3277 cx: &mut AsyncAppContext,
3278 ) -> Result<Vec<(Range<Anchor>, String)>> {
3279 let text_document =
3280 lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
3281 let capabilities = &language_server.capabilities();
3282 let lsp_edits = if capabilities
3283 .document_formatting_provider
3284 .as_ref()
3285 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3286 {
3287 language_server
3288 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3289 text_document,
3290 options: lsp::FormattingOptions {
3291 tab_size: tab_size.into(),
3292 insert_spaces: true,
3293 insert_final_newline: Some(true),
3294 ..Default::default()
3295 },
3296 work_done_progress_params: Default::default(),
3297 })
3298 .await?
3299 } else if capabilities
3300 .document_range_formatting_provider
3301 .as_ref()
3302 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3303 {
3304 let buffer_start = lsp::Position::new(0, 0);
3305 let buffer_end =
3306 buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3307 language_server
3308 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3309 text_document,
3310 range: lsp::Range::new(buffer_start, buffer_end),
3311 options: lsp::FormattingOptions {
3312 tab_size: tab_size.into(),
3313 insert_spaces: true,
3314 insert_final_newline: Some(true),
3315 ..Default::default()
3316 },
3317 work_done_progress_params: Default::default(),
3318 })
3319 .await?
3320 } else {
3321 None
3322 };
3323
3324 if let Some(lsp_edits) = lsp_edits {
3325 this.update(cx, |this, cx| {
3326 this.edits_from_lsp(buffer, lsp_edits, None, cx)
3327 })
3328 .await
3329 } else {
3330 Ok(Default::default())
3331 }
3332 }
3333
3334 async fn format_via_external_command(
3335 buffer: &ModelHandle<Buffer>,
3336 buffer_abs_path: &Path,
3337 command: &str,
3338 arguments: &[String],
3339 cx: &mut AsyncAppContext,
3340 ) -> Result<Option<Diff>> {
3341 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3342 let file = File::from_dyn(buffer.file())?;
3343 let worktree = file.worktree.read(cx).as_local()?;
3344 let mut worktree_path = worktree.abs_path().to_path_buf();
3345 if worktree.root_entry()?.is_file() {
3346 worktree_path.pop();
3347 }
3348 Some(worktree_path)
3349 });
3350
3351 if let Some(working_dir_path) = working_dir_path {
3352 let mut child =
3353 smol::process::Command::new(command)
3354 .args(arguments.iter().map(|arg| {
3355 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3356 }))
3357 .current_dir(&working_dir_path)
3358 .stdin(smol::process::Stdio::piped())
3359 .stdout(smol::process::Stdio::piped())
3360 .stderr(smol::process::Stdio::piped())
3361 .spawn()?;
3362 let stdin = child
3363 .stdin
3364 .as_mut()
3365 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3366 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3367 for chunk in text.chunks() {
3368 stdin.write_all(chunk.as_bytes()).await?;
3369 }
3370 stdin.flush().await?;
3371
3372 let output = child.output().await?;
3373 if !output.status.success() {
3374 return Err(anyhow!(
3375 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3376 output.status.code(),
3377 String::from_utf8_lossy(&output.stdout),
3378 String::from_utf8_lossy(&output.stderr),
3379 ));
3380 }
3381
3382 let stdout = String::from_utf8(output.stdout)?;
3383 Ok(Some(
3384 buffer
3385 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3386 .await,
3387 ))
3388 } else {
3389 Ok(None)
3390 }
3391 }
3392
3393 pub fn definition<T: ToPointUtf16>(
3394 &self,
3395 buffer: &ModelHandle<Buffer>,
3396 position: T,
3397 cx: &mut ModelContext<Self>,
3398 ) -> Task<Result<Vec<LocationLink>>> {
3399 let position = position.to_point_utf16(buffer.read(cx));
3400 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3401 }
3402
3403 pub fn type_definition<T: ToPointUtf16>(
3404 &self,
3405 buffer: &ModelHandle<Buffer>,
3406 position: T,
3407 cx: &mut ModelContext<Self>,
3408 ) -> Task<Result<Vec<LocationLink>>> {
3409 let position = position.to_point_utf16(buffer.read(cx));
3410 self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3411 }
3412
3413 pub fn references<T: ToPointUtf16>(
3414 &self,
3415 buffer: &ModelHandle<Buffer>,
3416 position: T,
3417 cx: &mut ModelContext<Self>,
3418 ) -> Task<Result<Vec<Location>>> {
3419 let position = position.to_point_utf16(buffer.read(cx));
3420 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3421 }
3422
3423 pub fn document_highlights<T: ToPointUtf16>(
3424 &self,
3425 buffer: &ModelHandle<Buffer>,
3426 position: T,
3427 cx: &mut ModelContext<Self>,
3428 ) -> Task<Result<Vec<DocumentHighlight>>> {
3429 let position = position.to_point_utf16(buffer.read(cx));
3430 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3431 }
3432
3433 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3434 if self.is_local() {
3435 let mut requests = Vec::new();
3436 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3437 let worktree_id = *worktree_id;
3438 if let Some(worktree) = self
3439 .worktree_for_id(worktree_id, cx)
3440 .and_then(|worktree| worktree.read(cx).as_local())
3441 {
3442 if let Some(LanguageServerState::Running {
3443 adapter,
3444 language,
3445 server,
3446 ..
3447 }) = self.language_servers.get(server_id)
3448 {
3449 let adapter = adapter.clone();
3450 let language = language.clone();
3451 let worktree_abs_path = worktree.abs_path().clone();
3452 requests.push(
3453 server
3454 .request::<lsp::request::WorkspaceSymbol>(
3455 lsp::WorkspaceSymbolParams {
3456 query: query.to_string(),
3457 ..Default::default()
3458 },
3459 )
3460 .log_err()
3461 .map(move |response| {
3462 (
3463 adapter,
3464 language,
3465 worktree_id,
3466 worktree_abs_path,
3467 response.unwrap_or_default(),
3468 )
3469 }),
3470 );
3471 }
3472 }
3473 }
3474
3475 cx.spawn_weak(|this, cx| async move {
3476 let responses = futures::future::join_all(requests).await;
3477 let this = if let Some(this) = this.upgrade(&cx) {
3478 this
3479 } else {
3480 return Ok(Default::default());
3481 };
3482 let symbols = this.read_with(&cx, |this, cx| {
3483 let mut symbols = Vec::new();
3484 for (
3485 adapter,
3486 adapter_language,
3487 source_worktree_id,
3488 worktree_abs_path,
3489 response,
3490 ) in responses
3491 {
3492 symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3493 let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3494 let mut worktree_id = source_worktree_id;
3495 let path;
3496 if let Some((worktree, rel_path)) =
3497 this.find_local_worktree(&abs_path, cx)
3498 {
3499 worktree_id = worktree.read(cx).id();
3500 path = rel_path;
3501 } else {
3502 path = relativize_path(&worktree_abs_path, &abs_path);
3503 }
3504
3505 let project_path = ProjectPath {
3506 worktree_id,
3507 path: path.into(),
3508 };
3509 let signature = this.symbol_signature(&project_path);
3510 let adapter_language = adapter_language.clone();
3511 let language = this
3512 .languages
3513 .language_for_file(&project_path.path, None)
3514 .unwrap_or_else(move |_| adapter_language);
3515 let language_server_name = adapter.name.clone();
3516 Some(async move {
3517 let language = language.await;
3518 let label = language
3519 .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3520 .await;
3521
3522 Symbol {
3523 language_server_name,
3524 source_worktree_id,
3525 path: project_path,
3526 label: label.unwrap_or_else(|| {
3527 CodeLabel::plain(lsp_symbol.name.clone(), None)
3528 }),
3529 kind: lsp_symbol.kind,
3530 name: lsp_symbol.name,
3531 range: range_from_lsp(lsp_symbol.location.range),
3532 signature,
3533 }
3534 })
3535 }));
3536 }
3537 symbols
3538 });
3539 Ok(futures::future::join_all(symbols).await)
3540 })
3541 } else if let Some(project_id) = self.remote_id() {
3542 let request = self.client.request(proto::GetProjectSymbols {
3543 project_id,
3544 query: query.to_string(),
3545 });
3546 cx.spawn_weak(|this, cx| async move {
3547 let response = request.await?;
3548 let mut symbols = Vec::new();
3549 if let Some(this) = this.upgrade(&cx) {
3550 let new_symbols = this.read_with(&cx, |this, _| {
3551 response
3552 .symbols
3553 .into_iter()
3554 .map(|symbol| this.deserialize_symbol(symbol))
3555 .collect::<Vec<_>>()
3556 });
3557 symbols = futures::future::join_all(new_symbols)
3558 .await
3559 .into_iter()
3560 .filter_map(|symbol| symbol.log_err())
3561 .collect::<Vec<_>>();
3562 }
3563 Ok(symbols)
3564 })
3565 } else {
3566 Task::ready(Ok(Default::default()))
3567 }
3568 }
3569
3570 pub fn open_buffer_for_symbol(
3571 &mut self,
3572 symbol: &Symbol,
3573 cx: &mut ModelContext<Self>,
3574 ) -> Task<Result<ModelHandle<Buffer>>> {
3575 if self.is_local() {
3576 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3577 symbol.source_worktree_id,
3578 symbol.language_server_name.clone(),
3579 )) {
3580 *id
3581 } else {
3582 return Task::ready(Err(anyhow!(
3583 "language server for worktree and language not found"
3584 )));
3585 };
3586
3587 let worktree_abs_path = if let Some(worktree_abs_path) = self
3588 .worktree_for_id(symbol.path.worktree_id, cx)
3589 .and_then(|worktree| worktree.read(cx).as_local())
3590 .map(|local_worktree| local_worktree.abs_path())
3591 {
3592 worktree_abs_path
3593 } else {
3594 return Task::ready(Err(anyhow!("worktree not found for symbol")));
3595 };
3596 let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3597 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3598 uri
3599 } else {
3600 return Task::ready(Err(anyhow!("invalid symbol path")));
3601 };
3602
3603 self.open_local_buffer_via_lsp(
3604 symbol_uri,
3605 language_server_id,
3606 symbol.language_server_name.clone(),
3607 cx,
3608 )
3609 } else if let Some(project_id) = self.remote_id() {
3610 let request = self.client.request(proto::OpenBufferForSymbol {
3611 project_id,
3612 symbol: Some(serialize_symbol(symbol)),
3613 });
3614 cx.spawn(|this, mut cx| async move {
3615 let response = request.await?;
3616 this.update(&mut cx, |this, cx| {
3617 this.wait_for_remote_buffer(response.buffer_id, cx)
3618 })
3619 .await
3620 })
3621 } else {
3622 Task::ready(Err(anyhow!("project does not have a remote id")))
3623 }
3624 }
3625
3626 pub fn hover<T: ToPointUtf16>(
3627 &self,
3628 buffer: &ModelHandle<Buffer>,
3629 position: T,
3630 cx: &mut ModelContext<Self>,
3631 ) -> Task<Result<Option<Hover>>> {
3632 let position = position.to_point_utf16(buffer.read(cx));
3633 self.request_lsp(buffer.clone(), GetHover { position }, cx)
3634 }
3635
3636 pub fn completions<T: ToPointUtf16>(
3637 &self,
3638 buffer: &ModelHandle<Buffer>,
3639 position: T,
3640 cx: &mut ModelContext<Self>,
3641 ) -> Task<Result<Vec<Completion>>> {
3642 let position = position.to_point_utf16(buffer.read(cx));
3643 self.request_lsp(buffer.clone(), GetCompletions { position }, cx)
3644 }
3645
3646 pub fn apply_additional_edits_for_completion(
3647 &self,
3648 buffer_handle: ModelHandle<Buffer>,
3649 completion: Completion,
3650 push_to_history: bool,
3651 cx: &mut ModelContext<Self>,
3652 ) -> Task<Result<Option<Transaction>>> {
3653 let buffer = buffer_handle.read(cx);
3654 let buffer_id = buffer.remote_id();
3655
3656 if self.is_local() {
3657 let lang_server = match self.language_server_for_buffer(buffer, cx) {
3658 Some((_, server)) => server.clone(),
3659 _ => return Task::ready(Ok(Default::default())),
3660 };
3661
3662 cx.spawn(|this, mut cx| async move {
3663 let resolved_completion = lang_server
3664 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3665 .await?;
3666
3667 if let Some(edits) = resolved_completion.additional_text_edits {
3668 let edits = this
3669 .update(&mut cx, |this, cx| {
3670 this.edits_from_lsp(&buffer_handle, edits, None, cx)
3671 })
3672 .await?;
3673
3674 buffer_handle.update(&mut cx, |buffer, cx| {
3675 buffer.finalize_last_transaction();
3676 buffer.start_transaction();
3677
3678 for (range, text) in edits {
3679 let primary = &completion.old_range;
3680 let start_within = primary.start.cmp(&range.start, buffer).is_le()
3681 && primary.end.cmp(&range.start, buffer).is_ge();
3682 let end_within = range.start.cmp(&primary.end, buffer).is_le()
3683 && range.end.cmp(&primary.end, buffer).is_ge();
3684
3685 //Skip addtional edits which overlap with the primary completion edit
3686 //https://github.com/zed-industries/zed/pull/1871
3687 if !start_within && !end_within {
3688 buffer.edit([(range, text)], None, cx);
3689 }
3690 }
3691
3692 let transaction = if buffer.end_transaction(cx).is_some() {
3693 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3694 if !push_to_history {
3695 buffer.forget_transaction(transaction.id);
3696 }
3697 Some(transaction)
3698 } else {
3699 None
3700 };
3701 Ok(transaction)
3702 })
3703 } else {
3704 Ok(None)
3705 }
3706 })
3707 } else if let Some(project_id) = self.remote_id() {
3708 let client = self.client.clone();
3709 cx.spawn(|_, mut cx| async move {
3710 let response = client
3711 .request(proto::ApplyCompletionAdditionalEdits {
3712 project_id,
3713 buffer_id,
3714 completion: Some(language::proto::serialize_completion(&completion)),
3715 })
3716 .await?;
3717
3718 if let Some(transaction) = response.transaction {
3719 let transaction = language::proto::deserialize_transaction(transaction)?;
3720 buffer_handle
3721 .update(&mut cx, |buffer, _| {
3722 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3723 })
3724 .await?;
3725 if push_to_history {
3726 buffer_handle.update(&mut cx, |buffer, _| {
3727 buffer.push_transaction(transaction.clone(), Instant::now());
3728 });
3729 }
3730 Ok(Some(transaction))
3731 } else {
3732 Ok(None)
3733 }
3734 })
3735 } else {
3736 Task::ready(Err(anyhow!("project does not have a remote id")))
3737 }
3738 }
3739
3740 pub fn code_actions<T: Clone + ToOffset>(
3741 &self,
3742 buffer_handle: &ModelHandle<Buffer>,
3743 range: Range<T>,
3744 cx: &mut ModelContext<Self>,
3745 ) -> Task<Result<Vec<CodeAction>>> {
3746 let buffer = buffer_handle.read(cx);
3747 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3748 self.request_lsp(buffer_handle.clone(), GetCodeActions { range }, cx)
3749 }
3750
3751 pub fn apply_code_action(
3752 &self,
3753 buffer_handle: ModelHandle<Buffer>,
3754 mut action: CodeAction,
3755 push_to_history: bool,
3756 cx: &mut ModelContext<Self>,
3757 ) -> Task<Result<ProjectTransaction>> {
3758 if self.is_local() {
3759 let buffer = buffer_handle.read(cx);
3760 let (lsp_adapter, lang_server) =
3761 if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3762 (adapter.clone(), server.clone())
3763 } else {
3764 return Task::ready(Ok(Default::default()));
3765 };
3766 let range = action.range.to_point_utf16(buffer);
3767
3768 cx.spawn(|this, mut cx| async move {
3769 if let Some(lsp_range) = action
3770 .lsp_action
3771 .data
3772 .as_mut()
3773 .and_then(|d| d.get_mut("codeActionParams"))
3774 .and_then(|d| d.get_mut("range"))
3775 {
3776 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3777 action.lsp_action = lang_server
3778 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3779 .await?;
3780 } else {
3781 let actions = this
3782 .update(&mut cx, |this, cx| {
3783 this.code_actions(&buffer_handle, action.range, cx)
3784 })
3785 .await?;
3786 action.lsp_action = actions
3787 .into_iter()
3788 .find(|a| a.lsp_action.title == action.lsp_action.title)
3789 .ok_or_else(|| anyhow!("code action is outdated"))?
3790 .lsp_action;
3791 }
3792
3793 if let Some(edit) = action.lsp_action.edit {
3794 if edit.changes.is_some() || edit.document_changes.is_some() {
3795 return Self::deserialize_workspace_edit(
3796 this,
3797 edit,
3798 push_to_history,
3799 lsp_adapter.clone(),
3800 lang_server.clone(),
3801 &mut cx,
3802 )
3803 .await;
3804 }
3805 }
3806
3807 if let Some(command) = action.lsp_action.command {
3808 this.update(&mut cx, |this, _| {
3809 this.last_workspace_edits_by_language_server
3810 .remove(&lang_server.server_id());
3811 });
3812 lang_server
3813 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3814 command: command.command,
3815 arguments: command.arguments.unwrap_or_default(),
3816 ..Default::default()
3817 })
3818 .await?;
3819 return Ok(this.update(&mut cx, |this, _| {
3820 this.last_workspace_edits_by_language_server
3821 .remove(&lang_server.server_id())
3822 .unwrap_or_default()
3823 }));
3824 }
3825
3826 Ok(ProjectTransaction::default())
3827 })
3828 } else if let Some(project_id) = self.remote_id() {
3829 let client = self.client.clone();
3830 let request = proto::ApplyCodeAction {
3831 project_id,
3832 buffer_id: buffer_handle.read(cx).remote_id(),
3833 action: Some(language::proto::serialize_code_action(&action)),
3834 };
3835 cx.spawn(|this, mut cx| async move {
3836 let response = client
3837 .request(request)
3838 .await?
3839 .transaction
3840 .ok_or_else(|| anyhow!("missing transaction"))?;
3841 this.update(&mut cx, |this, cx| {
3842 this.deserialize_project_transaction(response, push_to_history, cx)
3843 })
3844 .await
3845 })
3846 } else {
3847 Task::ready(Err(anyhow!("project does not have a remote id")))
3848 }
3849 }
3850
3851 async fn deserialize_workspace_edit(
3852 this: ModelHandle<Self>,
3853 edit: lsp::WorkspaceEdit,
3854 push_to_history: bool,
3855 lsp_adapter: Arc<CachedLspAdapter>,
3856 language_server: Arc<LanguageServer>,
3857 cx: &mut AsyncAppContext,
3858 ) -> Result<ProjectTransaction> {
3859 let fs = this.read_with(cx, |this, _| this.fs.clone());
3860 let mut operations = Vec::new();
3861 if let Some(document_changes) = edit.document_changes {
3862 match document_changes {
3863 lsp::DocumentChanges::Edits(edits) => {
3864 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3865 }
3866 lsp::DocumentChanges::Operations(ops) => operations = ops,
3867 }
3868 } else if let Some(changes) = edit.changes {
3869 operations.extend(changes.into_iter().map(|(uri, edits)| {
3870 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3871 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3872 uri,
3873 version: None,
3874 },
3875 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3876 })
3877 }));
3878 }
3879
3880 let mut project_transaction = ProjectTransaction::default();
3881 for operation in operations {
3882 match operation {
3883 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3884 let abs_path = op
3885 .uri
3886 .to_file_path()
3887 .map_err(|_| anyhow!("can't convert URI to path"))?;
3888
3889 if let Some(parent_path) = abs_path.parent() {
3890 fs.create_dir(parent_path).await?;
3891 }
3892 if abs_path.ends_with("/") {
3893 fs.create_dir(&abs_path).await?;
3894 } else {
3895 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3896 .await?;
3897 }
3898 }
3899 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3900 let source_abs_path = op
3901 .old_uri
3902 .to_file_path()
3903 .map_err(|_| anyhow!("can't convert URI to path"))?;
3904 let target_abs_path = op
3905 .new_uri
3906 .to_file_path()
3907 .map_err(|_| anyhow!("can't convert URI to path"))?;
3908 fs.rename(
3909 &source_abs_path,
3910 &target_abs_path,
3911 op.options.map(Into::into).unwrap_or_default(),
3912 )
3913 .await?;
3914 }
3915 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3916 let abs_path = op
3917 .uri
3918 .to_file_path()
3919 .map_err(|_| anyhow!("can't convert URI to path"))?;
3920 let options = op.options.map(Into::into).unwrap_or_default();
3921 if abs_path.ends_with("/") {
3922 fs.remove_dir(&abs_path, options).await?;
3923 } else {
3924 fs.remove_file(&abs_path, options).await?;
3925 }
3926 }
3927 lsp::DocumentChangeOperation::Edit(op) => {
3928 let buffer_to_edit = this
3929 .update(cx, |this, cx| {
3930 this.open_local_buffer_via_lsp(
3931 op.text_document.uri,
3932 language_server.server_id(),
3933 lsp_adapter.name.clone(),
3934 cx,
3935 )
3936 })
3937 .await?;
3938
3939 let edits = this
3940 .update(cx, |this, cx| {
3941 let edits = op.edits.into_iter().map(|edit| match edit {
3942 lsp::OneOf::Left(edit) => edit,
3943 lsp::OneOf::Right(edit) => edit.text_edit,
3944 });
3945 this.edits_from_lsp(
3946 &buffer_to_edit,
3947 edits,
3948 op.text_document.version,
3949 cx,
3950 )
3951 })
3952 .await?;
3953
3954 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3955 buffer.finalize_last_transaction();
3956 buffer.start_transaction();
3957 for (range, text) in edits {
3958 buffer.edit([(range, text)], None, cx);
3959 }
3960 let transaction = if buffer.end_transaction(cx).is_some() {
3961 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3962 if !push_to_history {
3963 buffer.forget_transaction(transaction.id);
3964 }
3965 Some(transaction)
3966 } else {
3967 None
3968 };
3969
3970 transaction
3971 });
3972 if let Some(transaction) = transaction {
3973 project_transaction.0.insert(buffer_to_edit, transaction);
3974 }
3975 }
3976 }
3977 }
3978
3979 Ok(project_transaction)
3980 }
3981
3982 pub fn prepare_rename<T: ToPointUtf16>(
3983 &self,
3984 buffer: ModelHandle<Buffer>,
3985 position: T,
3986 cx: &mut ModelContext<Self>,
3987 ) -> Task<Result<Option<Range<Anchor>>>> {
3988 let position = position.to_point_utf16(buffer.read(cx));
3989 self.request_lsp(buffer, PrepareRename { position }, cx)
3990 }
3991
3992 pub fn perform_rename<T: ToPointUtf16>(
3993 &self,
3994 buffer: ModelHandle<Buffer>,
3995 position: T,
3996 new_name: String,
3997 push_to_history: bool,
3998 cx: &mut ModelContext<Self>,
3999 ) -> Task<Result<ProjectTransaction>> {
4000 let position = position.to_point_utf16(buffer.read(cx));
4001 self.request_lsp(
4002 buffer,
4003 PerformRename {
4004 position,
4005 new_name,
4006 push_to_history,
4007 },
4008 cx,
4009 )
4010 }
4011
4012 #[allow(clippy::type_complexity)]
4013 pub fn search(
4014 &self,
4015 query: SearchQuery,
4016 cx: &mut ModelContext<Self>,
4017 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4018 if self.is_local() {
4019 let snapshots = self
4020 .visible_worktrees(cx)
4021 .filter_map(|tree| {
4022 let tree = tree.read(cx).as_local()?;
4023 Some(tree.snapshot())
4024 })
4025 .collect::<Vec<_>>();
4026
4027 let background = cx.background().clone();
4028 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4029 if path_count == 0 {
4030 return Task::ready(Ok(Default::default()));
4031 }
4032 let workers = background.num_cpus().min(path_count);
4033 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4034 cx.background()
4035 .spawn({
4036 let fs = self.fs.clone();
4037 let background = cx.background().clone();
4038 let query = query.clone();
4039 async move {
4040 let fs = &fs;
4041 let query = &query;
4042 let matching_paths_tx = &matching_paths_tx;
4043 let paths_per_worker = (path_count + workers - 1) / workers;
4044 let snapshots = &snapshots;
4045 background
4046 .scoped(|scope| {
4047 for worker_ix in 0..workers {
4048 let worker_start_ix = worker_ix * paths_per_worker;
4049 let worker_end_ix = worker_start_ix + paths_per_worker;
4050 scope.spawn(async move {
4051 let mut snapshot_start_ix = 0;
4052 let mut abs_path = PathBuf::new();
4053 for snapshot in snapshots {
4054 let snapshot_end_ix =
4055 snapshot_start_ix + snapshot.visible_file_count();
4056 if worker_end_ix <= snapshot_start_ix {
4057 break;
4058 } else if worker_start_ix > snapshot_end_ix {
4059 snapshot_start_ix = snapshot_end_ix;
4060 continue;
4061 } else {
4062 let start_in_snapshot = worker_start_ix
4063 .saturating_sub(snapshot_start_ix);
4064 let end_in_snapshot =
4065 cmp::min(worker_end_ix, snapshot_end_ix)
4066 - snapshot_start_ix;
4067
4068 for entry in snapshot
4069 .files(false, start_in_snapshot)
4070 .take(end_in_snapshot - start_in_snapshot)
4071 {
4072 if matching_paths_tx.is_closed() {
4073 break;
4074 }
4075
4076 abs_path.clear();
4077 abs_path.push(&snapshot.abs_path());
4078 abs_path.push(&entry.path);
4079 let matches = if let Some(file) =
4080 fs.open_sync(&abs_path).await.log_err()
4081 {
4082 query.detect(file).unwrap_or(false)
4083 } else {
4084 false
4085 };
4086
4087 if matches {
4088 let project_path =
4089 (snapshot.id(), entry.path.clone());
4090 if matching_paths_tx
4091 .send(project_path)
4092 .await
4093 .is_err()
4094 {
4095 break;
4096 }
4097 }
4098 }
4099
4100 snapshot_start_ix = snapshot_end_ix;
4101 }
4102 }
4103 });
4104 }
4105 })
4106 .await;
4107 }
4108 })
4109 .detach();
4110
4111 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4112 let open_buffers = self
4113 .opened_buffers
4114 .values()
4115 .filter_map(|b| b.upgrade(cx))
4116 .collect::<HashSet<_>>();
4117 cx.spawn(|this, cx| async move {
4118 for buffer in &open_buffers {
4119 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4120 buffers_tx.send((buffer.clone(), snapshot)).await?;
4121 }
4122
4123 let open_buffers = Rc::new(RefCell::new(open_buffers));
4124 while let Some(project_path) = matching_paths_rx.next().await {
4125 if buffers_tx.is_closed() {
4126 break;
4127 }
4128
4129 let this = this.clone();
4130 let open_buffers = open_buffers.clone();
4131 let buffers_tx = buffers_tx.clone();
4132 cx.spawn(|mut cx| async move {
4133 if let Some(buffer) = this
4134 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4135 .await
4136 .log_err()
4137 {
4138 if open_buffers.borrow_mut().insert(buffer.clone()) {
4139 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4140 buffers_tx.send((buffer, snapshot)).await?;
4141 }
4142 }
4143
4144 Ok::<_, anyhow::Error>(())
4145 })
4146 .detach();
4147 }
4148
4149 Ok::<_, anyhow::Error>(())
4150 })
4151 .detach_and_log_err(cx);
4152
4153 let background = cx.background().clone();
4154 cx.background().spawn(async move {
4155 let query = &query;
4156 let mut matched_buffers = Vec::new();
4157 for _ in 0..workers {
4158 matched_buffers.push(HashMap::default());
4159 }
4160 background
4161 .scoped(|scope| {
4162 for worker_matched_buffers in matched_buffers.iter_mut() {
4163 let mut buffers_rx = buffers_rx.clone();
4164 scope.spawn(async move {
4165 while let Some((buffer, snapshot)) = buffers_rx.next().await {
4166 let buffer_matches = query
4167 .search(snapshot.as_rope())
4168 .await
4169 .iter()
4170 .map(|range| {
4171 snapshot.anchor_before(range.start)
4172 ..snapshot.anchor_after(range.end)
4173 })
4174 .collect::<Vec<_>>();
4175 if !buffer_matches.is_empty() {
4176 worker_matched_buffers
4177 .insert(buffer.clone(), buffer_matches);
4178 }
4179 }
4180 });
4181 }
4182 })
4183 .await;
4184 Ok(matched_buffers.into_iter().flatten().collect())
4185 })
4186 } else if let Some(project_id) = self.remote_id() {
4187 let request = self.client.request(query.to_proto(project_id));
4188 cx.spawn(|this, mut cx| async move {
4189 let response = request.await?;
4190 let mut result = HashMap::default();
4191 for location in response.locations {
4192 let target_buffer = this
4193 .update(&mut cx, |this, cx| {
4194 this.wait_for_remote_buffer(location.buffer_id, cx)
4195 })
4196 .await?;
4197 let start = location
4198 .start
4199 .and_then(deserialize_anchor)
4200 .ok_or_else(|| anyhow!("missing target start"))?;
4201 let end = location
4202 .end
4203 .and_then(deserialize_anchor)
4204 .ok_or_else(|| anyhow!("missing target end"))?;
4205 result
4206 .entry(target_buffer)
4207 .or_insert(Vec::new())
4208 .push(start..end)
4209 }
4210 Ok(result)
4211 })
4212 } else {
4213 Task::ready(Ok(Default::default()))
4214 }
4215 }
4216
4217 fn request_lsp<R: LspCommand>(
4218 &self,
4219 buffer_handle: ModelHandle<Buffer>,
4220 request: R,
4221 cx: &mut ModelContext<Self>,
4222 ) -> Task<Result<R::Response>>
4223 where
4224 <R::LspRequest as lsp::request::Request>::Result: Send,
4225 {
4226 let buffer = buffer_handle.read(cx);
4227 if self.is_local() {
4228 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4229 if let Some((file, language_server)) = file.zip(
4230 self.language_server_for_buffer(buffer, cx)
4231 .map(|(_, server)| server.clone()),
4232 ) {
4233 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
4234 return cx.spawn(|this, cx| async move {
4235 if !request.check_capabilities(language_server.capabilities()) {
4236 return Ok(Default::default());
4237 }
4238
4239 let response = language_server
4240 .request::<R::LspRequest>(lsp_params)
4241 .await
4242 .context("lsp request failed")?;
4243 request
4244 .response_from_lsp(response, this, buffer_handle, cx)
4245 .await
4246 });
4247 }
4248 } else if let Some(project_id) = self.remote_id() {
4249 let rpc = self.client.clone();
4250 let message = request.to_proto(project_id, buffer);
4251 return cx.spawn_weak(|this, cx| async move {
4252 // Ensure the project is still alive by the time the task
4253 // is scheduled.
4254 this.upgrade(&cx)
4255 .ok_or_else(|| anyhow!("project dropped"))?;
4256
4257 let response = rpc.request(message).await?;
4258
4259 let this = this
4260 .upgrade(&cx)
4261 .ok_or_else(|| anyhow!("project dropped"))?;
4262 if this.read_with(&cx, |this, _| this.is_read_only()) {
4263 Err(anyhow!("disconnected before completing request"))
4264 } else {
4265 request
4266 .response_from_proto(response, this, buffer_handle, cx)
4267 .await
4268 }
4269 });
4270 }
4271 Task::ready(Ok(Default::default()))
4272 }
4273
4274 pub fn find_or_create_local_worktree(
4275 &mut self,
4276 abs_path: impl AsRef<Path>,
4277 visible: bool,
4278 cx: &mut ModelContext<Self>,
4279 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4280 let abs_path = abs_path.as_ref();
4281 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4282 Task::ready(Ok((tree, relative_path)))
4283 } else {
4284 let worktree = self.create_local_worktree(abs_path, visible, cx);
4285 cx.foreground()
4286 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4287 }
4288 }
4289
4290 pub fn find_local_worktree(
4291 &self,
4292 abs_path: &Path,
4293 cx: &AppContext,
4294 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4295 for tree in &self.worktrees {
4296 if let Some(tree) = tree.upgrade(cx) {
4297 if let Some(relative_path) = tree
4298 .read(cx)
4299 .as_local()
4300 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4301 {
4302 return Some((tree.clone(), relative_path.into()));
4303 }
4304 }
4305 }
4306 None
4307 }
4308
4309 pub fn is_shared(&self) -> bool {
4310 match &self.client_state {
4311 Some(ProjectClientState::Local { .. }) => true,
4312 _ => false,
4313 }
4314 }
4315
4316 fn create_local_worktree(
4317 &mut self,
4318 abs_path: impl AsRef<Path>,
4319 visible: bool,
4320 cx: &mut ModelContext<Self>,
4321 ) -> Task<Result<ModelHandle<Worktree>>> {
4322 let fs = self.fs.clone();
4323 let client = self.client.clone();
4324 let next_entry_id = self.next_entry_id.clone();
4325 let path: Arc<Path> = abs_path.as_ref().into();
4326 let task = self
4327 .loading_local_worktrees
4328 .entry(path.clone())
4329 .or_insert_with(|| {
4330 cx.spawn(|project, mut cx| {
4331 async move {
4332 let worktree = Worktree::local(
4333 client.clone(),
4334 path.clone(),
4335 visible,
4336 fs,
4337 next_entry_id,
4338 &mut cx,
4339 )
4340 .await;
4341
4342 project.update(&mut cx, |project, _| {
4343 project.loading_local_worktrees.remove(&path);
4344 });
4345
4346 let worktree = worktree?;
4347 project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
4348 Ok(worktree)
4349 }
4350 .map_err(Arc::new)
4351 })
4352 .shared()
4353 })
4354 .clone();
4355 cx.foreground().spawn(async move {
4356 match task.await {
4357 Ok(worktree) => Ok(worktree),
4358 Err(err) => Err(anyhow!("{}", err)),
4359 }
4360 })
4361 }
4362
4363 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4364 self.worktrees.retain(|worktree| {
4365 if let Some(worktree) = worktree.upgrade(cx) {
4366 let id = worktree.read(cx).id();
4367 if id == id_to_remove {
4368 cx.emit(Event::WorktreeRemoved(id));
4369 false
4370 } else {
4371 true
4372 }
4373 } else {
4374 false
4375 }
4376 });
4377 self.metadata_changed(cx);
4378 }
4379
4380 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4381 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4382 if worktree.read(cx).is_local() {
4383 cx.subscribe(worktree, |this, worktree, event, cx| match event {
4384 worktree::Event::UpdatedEntries(changes) => {
4385 this.update_local_worktree_buffers(&worktree, cx);
4386 this.update_local_worktree_language_servers(&worktree, changes, cx);
4387 }
4388 worktree::Event::UpdatedGitRepositories(updated_repos) => {
4389 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4390 }
4391 })
4392 .detach();
4393 }
4394
4395 let push_strong_handle = {
4396 let worktree = worktree.read(cx);
4397 self.is_shared() || worktree.is_visible() || worktree.is_remote()
4398 };
4399 if push_strong_handle {
4400 self.worktrees
4401 .push(WorktreeHandle::Strong(worktree.clone()));
4402 } else {
4403 self.worktrees
4404 .push(WorktreeHandle::Weak(worktree.downgrade()));
4405 }
4406
4407 cx.observe_release(worktree, |this, worktree, cx| {
4408 let _ = this.remove_worktree(worktree.id(), cx);
4409 })
4410 .detach();
4411
4412 cx.emit(Event::WorktreeAdded);
4413 self.metadata_changed(cx);
4414 }
4415
4416 fn update_local_worktree_buffers(
4417 &mut self,
4418 worktree_handle: &ModelHandle<Worktree>,
4419 cx: &mut ModelContext<Self>,
4420 ) {
4421 let snapshot = worktree_handle.read(cx).snapshot();
4422 let mut buffers_to_delete = Vec::new();
4423 let mut renamed_buffers = Vec::new();
4424 for (buffer_id, buffer) in &self.opened_buffers {
4425 if let Some(buffer) = buffer.upgrade(cx) {
4426 buffer.update(cx, |buffer, cx| {
4427 if let Some(old_file) = File::from_dyn(buffer.file()) {
4428 if old_file.worktree != *worktree_handle {
4429 return;
4430 }
4431
4432 let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id)
4433 {
4434 File {
4435 is_local: true,
4436 entry_id: entry.id,
4437 mtime: entry.mtime,
4438 path: entry.path.clone(),
4439 worktree: worktree_handle.clone(),
4440 is_deleted: false,
4441 }
4442 } else if let Some(entry) =
4443 snapshot.entry_for_path(old_file.path().as_ref())
4444 {
4445 File {
4446 is_local: true,
4447 entry_id: entry.id,
4448 mtime: entry.mtime,
4449 path: entry.path.clone(),
4450 worktree: worktree_handle.clone(),
4451 is_deleted: false,
4452 }
4453 } else {
4454 File {
4455 is_local: true,
4456 entry_id: old_file.entry_id,
4457 path: old_file.path().clone(),
4458 mtime: old_file.mtime(),
4459 worktree: worktree_handle.clone(),
4460 is_deleted: true,
4461 }
4462 };
4463
4464 let old_path = old_file.abs_path(cx);
4465 if new_file.abs_path(cx) != old_path {
4466 renamed_buffers.push((cx.handle(), old_path));
4467 }
4468
4469 if new_file != *old_file {
4470 if let Some(project_id) = self.remote_id() {
4471 self.client
4472 .send(proto::UpdateBufferFile {
4473 project_id,
4474 buffer_id: *buffer_id as u64,
4475 file: Some(new_file.to_proto()),
4476 })
4477 .log_err();
4478 }
4479
4480 buffer.file_updated(Arc::new(new_file), cx).detach();
4481 }
4482 }
4483 });
4484 } else {
4485 buffers_to_delete.push(*buffer_id);
4486 }
4487 }
4488
4489 for buffer_id in buffers_to_delete {
4490 self.opened_buffers.remove(&buffer_id);
4491 }
4492
4493 for (buffer, old_path) in renamed_buffers {
4494 self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4495 self.detect_language_for_buffer(&buffer, cx);
4496 self.register_buffer_with_language_server(&buffer, cx);
4497 }
4498 }
4499
4500 fn update_local_worktree_language_servers(
4501 &mut self,
4502 worktree_handle: &ModelHandle<Worktree>,
4503 changes: &HashMap<Arc<Path>, PathChange>,
4504 cx: &mut ModelContext<Self>,
4505 ) {
4506 let worktree_id = worktree_handle.read(cx).id();
4507 let abs_path = worktree_handle.read(cx).abs_path();
4508 for ((server_worktree_id, _), server_id) in &self.language_server_ids {
4509 if *server_worktree_id == worktree_id {
4510 if let Some(server) = self.language_servers.get(server_id) {
4511 if let LanguageServerState::Running {
4512 server,
4513 watched_paths,
4514 ..
4515 } = server
4516 {
4517 let params = lsp::DidChangeWatchedFilesParams {
4518 changes: changes
4519 .iter()
4520 .filter_map(|(path, change)| {
4521 let path = abs_path.join(path);
4522 if watched_paths.matches(&path) {
4523 Some(lsp::FileEvent {
4524 uri: lsp::Url::from_file_path(path).unwrap(),
4525 typ: match change {
4526 PathChange::Added => lsp::FileChangeType::CREATED,
4527 PathChange::Removed => lsp::FileChangeType::DELETED,
4528 PathChange::Updated
4529 | PathChange::AddedOrUpdated => {
4530 lsp::FileChangeType::CHANGED
4531 }
4532 },
4533 })
4534 } else {
4535 None
4536 }
4537 })
4538 .collect(),
4539 };
4540
4541 if !params.changes.is_empty() {
4542 server
4543 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
4544 .log_err();
4545 }
4546 }
4547 }
4548 }
4549 }
4550 }
4551
4552 fn update_local_worktree_buffers_git_repos(
4553 &mut self,
4554 worktree: ModelHandle<Worktree>,
4555 repos: &[GitRepositoryEntry],
4556 cx: &mut ModelContext<Self>,
4557 ) {
4558 for (_, buffer) in &self.opened_buffers {
4559 if let Some(buffer) = buffer.upgrade(cx) {
4560 let file = match File::from_dyn(buffer.read(cx).file()) {
4561 Some(file) => file,
4562 None => continue,
4563 };
4564 if file.worktree != worktree {
4565 continue;
4566 }
4567
4568 let path = file.path().clone();
4569
4570 let repo = match repos.iter().find(|repo| repo.manages(&path)) {
4571 Some(repo) => repo.clone(),
4572 None => return,
4573 };
4574
4575 let relative_repo = match path.strip_prefix(repo.content_path) {
4576 Ok(relative_repo) => relative_repo.to_owned(),
4577 Err(_) => return,
4578 };
4579
4580 let remote_id = self.remote_id();
4581 let client = self.client.clone();
4582
4583 cx.spawn(|_, mut cx| async move {
4584 let diff_base = cx
4585 .background()
4586 .spawn(async move { repo.repo.lock().load_index_text(&relative_repo) })
4587 .await;
4588
4589 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4590 buffer.set_diff_base(diff_base.clone(), cx);
4591 buffer.remote_id()
4592 });
4593
4594 if let Some(project_id) = remote_id {
4595 client
4596 .send(proto::UpdateDiffBase {
4597 project_id,
4598 buffer_id: buffer_id as u64,
4599 diff_base,
4600 })
4601 .log_err();
4602 }
4603 })
4604 .detach();
4605 }
4606 }
4607 }
4608
4609 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4610 let new_active_entry = entry.and_then(|project_path| {
4611 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4612 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4613 Some(entry.id)
4614 });
4615 if new_active_entry != self.active_entry {
4616 self.active_entry = new_active_entry;
4617 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4618 }
4619 }
4620
4621 pub fn language_servers_running_disk_based_diagnostics(
4622 &self,
4623 ) -> impl Iterator<Item = usize> + '_ {
4624 self.language_server_statuses
4625 .iter()
4626 .filter_map(|(id, status)| {
4627 if status.has_pending_diagnostic_updates {
4628 Some(*id)
4629 } else {
4630 None
4631 }
4632 })
4633 }
4634
4635 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4636 let mut summary = DiagnosticSummary::default();
4637 for (_, path_summary) in self.diagnostic_summaries(cx) {
4638 summary.error_count += path_summary.error_count;
4639 summary.warning_count += path_summary.warning_count;
4640 }
4641 summary
4642 }
4643
4644 pub fn diagnostic_summaries<'a>(
4645 &'a self,
4646 cx: &'a AppContext,
4647 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4648 self.visible_worktrees(cx).flat_map(move |worktree| {
4649 let worktree = worktree.read(cx);
4650 let worktree_id = worktree.id();
4651 worktree
4652 .diagnostic_summaries()
4653 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4654 })
4655 }
4656
4657 pub fn disk_based_diagnostics_started(
4658 &mut self,
4659 language_server_id: usize,
4660 cx: &mut ModelContext<Self>,
4661 ) {
4662 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4663 }
4664
4665 pub fn disk_based_diagnostics_finished(
4666 &mut self,
4667 language_server_id: usize,
4668 cx: &mut ModelContext<Self>,
4669 ) {
4670 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4671 }
4672
4673 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4674 self.active_entry
4675 }
4676
4677 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4678 self.worktree_for_id(path.worktree_id, cx)?
4679 .read(cx)
4680 .entry_for_path(&path.path)
4681 .cloned()
4682 }
4683
4684 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4685 let worktree = self.worktree_for_entry(entry_id, cx)?;
4686 let worktree = worktree.read(cx);
4687 let worktree_id = worktree.id();
4688 let path = worktree.entry_for_id(entry_id)?.path.clone();
4689 Some(ProjectPath { worktree_id, path })
4690 }
4691
4692 // RPC message handlers
4693
4694 async fn handle_unshare_project(
4695 this: ModelHandle<Self>,
4696 _: TypedEnvelope<proto::UnshareProject>,
4697 _: Arc<Client>,
4698 mut cx: AsyncAppContext,
4699 ) -> Result<()> {
4700 this.update(&mut cx, |this, cx| {
4701 if this.is_local() {
4702 this.unshare(cx)?;
4703 } else {
4704 this.disconnected_from_host(cx);
4705 }
4706 Ok(())
4707 })
4708 }
4709
4710 async fn handle_add_collaborator(
4711 this: ModelHandle<Self>,
4712 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4713 _: Arc<Client>,
4714 mut cx: AsyncAppContext,
4715 ) -> Result<()> {
4716 let collaborator = envelope
4717 .payload
4718 .collaborator
4719 .take()
4720 .ok_or_else(|| anyhow!("empty collaborator"))?;
4721
4722 let collaborator = Collaborator::from_proto(collaborator)?;
4723 this.update(&mut cx, |this, cx| {
4724 this.shared_buffers.remove(&collaborator.peer_id);
4725 this.collaborators
4726 .insert(collaborator.peer_id, collaborator);
4727 cx.notify();
4728 });
4729
4730 Ok(())
4731 }
4732
4733 async fn handle_update_project_collaborator(
4734 this: ModelHandle<Self>,
4735 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4736 _: Arc<Client>,
4737 mut cx: AsyncAppContext,
4738 ) -> Result<()> {
4739 let old_peer_id = envelope
4740 .payload
4741 .old_peer_id
4742 .ok_or_else(|| anyhow!("missing old peer id"))?;
4743 let new_peer_id = envelope
4744 .payload
4745 .new_peer_id
4746 .ok_or_else(|| anyhow!("missing new peer id"))?;
4747 this.update(&mut cx, |this, cx| {
4748 let collaborator = this
4749 .collaborators
4750 .remove(&old_peer_id)
4751 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4752 let is_host = collaborator.replica_id == 0;
4753 this.collaborators.insert(new_peer_id, collaborator);
4754
4755 let buffers = this.shared_buffers.remove(&old_peer_id);
4756 log::info!(
4757 "peer {} became {}. moving buffers {:?}",
4758 old_peer_id,
4759 new_peer_id,
4760 &buffers
4761 );
4762 if let Some(buffers) = buffers {
4763 this.shared_buffers.insert(new_peer_id, buffers);
4764 }
4765
4766 if is_host {
4767 this.opened_buffers
4768 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
4769 this.buffer_changes_tx
4770 .unbounded_send(BufferMessage::Resync)
4771 .unwrap();
4772 }
4773
4774 cx.emit(Event::CollaboratorUpdated {
4775 old_peer_id,
4776 new_peer_id,
4777 });
4778 cx.notify();
4779 Ok(())
4780 })
4781 }
4782
4783 async fn handle_remove_collaborator(
4784 this: ModelHandle<Self>,
4785 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4786 _: Arc<Client>,
4787 mut cx: AsyncAppContext,
4788 ) -> Result<()> {
4789 this.update(&mut cx, |this, cx| {
4790 let peer_id = envelope
4791 .payload
4792 .peer_id
4793 .ok_or_else(|| anyhow!("invalid peer id"))?;
4794 let replica_id = this
4795 .collaborators
4796 .remove(&peer_id)
4797 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4798 .replica_id;
4799 for buffer in this.opened_buffers.values() {
4800 if let Some(buffer) = buffer.upgrade(cx) {
4801 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4802 }
4803 }
4804 this.shared_buffers.remove(&peer_id);
4805
4806 cx.emit(Event::CollaboratorLeft(peer_id));
4807 cx.notify();
4808 Ok(())
4809 })
4810 }
4811
4812 async fn handle_update_project(
4813 this: ModelHandle<Self>,
4814 envelope: TypedEnvelope<proto::UpdateProject>,
4815 _: Arc<Client>,
4816 mut cx: AsyncAppContext,
4817 ) -> Result<()> {
4818 this.update(&mut cx, |this, cx| {
4819 // Don't handle messages that were sent before the response to us joining the project
4820 if envelope.message_id > this.join_project_response_message_id {
4821 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4822 }
4823 Ok(())
4824 })
4825 }
4826
4827 async fn handle_update_worktree(
4828 this: ModelHandle<Self>,
4829 envelope: TypedEnvelope<proto::UpdateWorktree>,
4830 _: Arc<Client>,
4831 mut cx: AsyncAppContext,
4832 ) -> Result<()> {
4833 this.update(&mut cx, |this, cx| {
4834 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4835 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4836 worktree.update(cx, |worktree, _| {
4837 let worktree = worktree.as_remote_mut().unwrap();
4838 worktree.update_from_remote(envelope.payload);
4839 });
4840 }
4841 Ok(())
4842 })
4843 }
4844
4845 async fn handle_create_project_entry(
4846 this: ModelHandle<Self>,
4847 envelope: TypedEnvelope<proto::CreateProjectEntry>,
4848 _: Arc<Client>,
4849 mut cx: AsyncAppContext,
4850 ) -> Result<proto::ProjectEntryResponse> {
4851 let worktree = this.update(&mut cx, |this, cx| {
4852 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4853 this.worktree_for_id(worktree_id, cx)
4854 .ok_or_else(|| anyhow!("worktree not found"))
4855 })?;
4856 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4857 let entry = worktree
4858 .update(&mut cx, |worktree, cx| {
4859 let worktree = worktree.as_local_mut().unwrap();
4860 let path = PathBuf::from(envelope.payload.path);
4861 worktree.create_entry(path, envelope.payload.is_directory, cx)
4862 })
4863 .await?;
4864 Ok(proto::ProjectEntryResponse {
4865 entry: Some((&entry).into()),
4866 worktree_scan_id: worktree_scan_id as u64,
4867 })
4868 }
4869
4870 async fn handle_rename_project_entry(
4871 this: ModelHandle<Self>,
4872 envelope: TypedEnvelope<proto::RenameProjectEntry>,
4873 _: Arc<Client>,
4874 mut cx: AsyncAppContext,
4875 ) -> Result<proto::ProjectEntryResponse> {
4876 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4877 let worktree = this.read_with(&cx, |this, cx| {
4878 this.worktree_for_entry(entry_id, cx)
4879 .ok_or_else(|| anyhow!("worktree not found"))
4880 })?;
4881 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4882 let entry = worktree
4883 .update(&mut cx, |worktree, cx| {
4884 let new_path = PathBuf::from(envelope.payload.new_path);
4885 worktree
4886 .as_local_mut()
4887 .unwrap()
4888 .rename_entry(entry_id, new_path, cx)
4889 .ok_or_else(|| anyhow!("invalid entry"))
4890 })?
4891 .await?;
4892 Ok(proto::ProjectEntryResponse {
4893 entry: Some((&entry).into()),
4894 worktree_scan_id: worktree_scan_id as u64,
4895 })
4896 }
4897
4898 async fn handle_copy_project_entry(
4899 this: ModelHandle<Self>,
4900 envelope: TypedEnvelope<proto::CopyProjectEntry>,
4901 _: Arc<Client>,
4902 mut cx: AsyncAppContext,
4903 ) -> Result<proto::ProjectEntryResponse> {
4904 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4905 let worktree = this.read_with(&cx, |this, cx| {
4906 this.worktree_for_entry(entry_id, cx)
4907 .ok_or_else(|| anyhow!("worktree not found"))
4908 })?;
4909 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4910 let entry = worktree
4911 .update(&mut cx, |worktree, cx| {
4912 let new_path = PathBuf::from(envelope.payload.new_path);
4913 worktree
4914 .as_local_mut()
4915 .unwrap()
4916 .copy_entry(entry_id, new_path, cx)
4917 .ok_or_else(|| anyhow!("invalid entry"))
4918 })?
4919 .await?;
4920 Ok(proto::ProjectEntryResponse {
4921 entry: Some((&entry).into()),
4922 worktree_scan_id: worktree_scan_id as u64,
4923 })
4924 }
4925
4926 async fn handle_delete_project_entry(
4927 this: ModelHandle<Self>,
4928 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4929 _: Arc<Client>,
4930 mut cx: AsyncAppContext,
4931 ) -> Result<proto::ProjectEntryResponse> {
4932 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4933 let worktree = this.read_with(&cx, |this, cx| {
4934 this.worktree_for_entry(entry_id, cx)
4935 .ok_or_else(|| anyhow!("worktree not found"))
4936 })?;
4937 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4938 worktree
4939 .update(&mut cx, |worktree, cx| {
4940 worktree
4941 .as_local_mut()
4942 .unwrap()
4943 .delete_entry(entry_id, cx)
4944 .ok_or_else(|| anyhow!("invalid entry"))
4945 })?
4946 .await?;
4947 Ok(proto::ProjectEntryResponse {
4948 entry: None,
4949 worktree_scan_id: worktree_scan_id as u64,
4950 })
4951 }
4952
4953 async fn handle_update_diagnostic_summary(
4954 this: ModelHandle<Self>,
4955 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4956 _: Arc<Client>,
4957 mut cx: AsyncAppContext,
4958 ) -> Result<()> {
4959 this.update(&mut cx, |this, cx| {
4960 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4961 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4962 if let Some(summary) = envelope.payload.summary {
4963 let project_path = ProjectPath {
4964 worktree_id,
4965 path: Path::new(&summary.path).into(),
4966 };
4967 worktree.update(cx, |worktree, _| {
4968 worktree
4969 .as_remote_mut()
4970 .unwrap()
4971 .update_diagnostic_summary(project_path.path.clone(), &summary);
4972 });
4973 cx.emit(Event::DiagnosticsUpdated {
4974 language_server_id: summary.language_server_id as usize,
4975 path: project_path,
4976 });
4977 }
4978 }
4979 Ok(())
4980 })
4981 }
4982
4983 async fn handle_start_language_server(
4984 this: ModelHandle<Self>,
4985 envelope: TypedEnvelope<proto::StartLanguageServer>,
4986 _: Arc<Client>,
4987 mut cx: AsyncAppContext,
4988 ) -> Result<()> {
4989 let server = envelope
4990 .payload
4991 .server
4992 .ok_or_else(|| anyhow!("invalid server"))?;
4993 this.update(&mut cx, |this, cx| {
4994 this.language_server_statuses.insert(
4995 server.id as usize,
4996 LanguageServerStatus {
4997 name: server.name,
4998 pending_work: Default::default(),
4999 has_pending_diagnostic_updates: false,
5000 progress_tokens: Default::default(),
5001 },
5002 );
5003 cx.notify();
5004 });
5005 Ok(())
5006 }
5007
5008 async fn handle_update_language_server(
5009 this: ModelHandle<Self>,
5010 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5011 _: Arc<Client>,
5012 mut cx: AsyncAppContext,
5013 ) -> Result<()> {
5014 this.update(&mut cx, |this, cx| {
5015 let language_server_id = envelope.payload.language_server_id as usize;
5016
5017 match envelope
5018 .payload
5019 .variant
5020 .ok_or_else(|| anyhow!("invalid variant"))?
5021 {
5022 proto::update_language_server::Variant::WorkStart(payload) => {
5023 this.on_lsp_work_start(
5024 language_server_id,
5025 payload.token,
5026 LanguageServerProgress {
5027 message: payload.message,
5028 percentage: payload.percentage.map(|p| p as usize),
5029 last_update_at: Instant::now(),
5030 },
5031 cx,
5032 );
5033 }
5034
5035 proto::update_language_server::Variant::WorkProgress(payload) => {
5036 this.on_lsp_work_progress(
5037 language_server_id,
5038 payload.token,
5039 LanguageServerProgress {
5040 message: payload.message,
5041 percentage: payload.percentage.map(|p| p as usize),
5042 last_update_at: Instant::now(),
5043 },
5044 cx,
5045 );
5046 }
5047
5048 proto::update_language_server::Variant::WorkEnd(payload) => {
5049 this.on_lsp_work_end(language_server_id, payload.token, cx);
5050 }
5051
5052 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5053 this.disk_based_diagnostics_started(language_server_id, cx);
5054 }
5055
5056 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5057 this.disk_based_diagnostics_finished(language_server_id, cx)
5058 }
5059 }
5060
5061 Ok(())
5062 })
5063 }
5064
5065 async fn handle_update_buffer(
5066 this: ModelHandle<Self>,
5067 envelope: TypedEnvelope<proto::UpdateBuffer>,
5068 _: Arc<Client>,
5069 mut cx: AsyncAppContext,
5070 ) -> Result<proto::Ack> {
5071 this.update(&mut cx, |this, cx| {
5072 let payload = envelope.payload.clone();
5073 let buffer_id = payload.buffer_id;
5074 let ops = payload
5075 .operations
5076 .into_iter()
5077 .map(language::proto::deserialize_operation)
5078 .collect::<Result<Vec<_>, _>>()?;
5079 let is_remote = this.is_remote();
5080 match this.opened_buffers.entry(buffer_id) {
5081 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5082 OpenBuffer::Strong(buffer) => {
5083 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5084 }
5085 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5086 OpenBuffer::Weak(_) => {}
5087 },
5088 hash_map::Entry::Vacant(e) => {
5089 assert!(
5090 is_remote,
5091 "received buffer update from {:?}",
5092 envelope.original_sender_id
5093 );
5094 e.insert(OpenBuffer::Operations(ops));
5095 }
5096 }
5097 Ok(proto::Ack {})
5098 })
5099 }
5100
5101 async fn handle_create_buffer_for_peer(
5102 this: ModelHandle<Self>,
5103 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5104 _: Arc<Client>,
5105 mut cx: AsyncAppContext,
5106 ) -> Result<()> {
5107 this.update(&mut cx, |this, cx| {
5108 match envelope
5109 .payload
5110 .variant
5111 .ok_or_else(|| anyhow!("missing variant"))?
5112 {
5113 proto::create_buffer_for_peer::Variant::State(mut state) => {
5114 let mut buffer_file = None;
5115 if let Some(file) = state.file.take() {
5116 let worktree_id = WorktreeId::from_proto(file.worktree_id);
5117 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5118 anyhow!("no worktree found for id {}", file.worktree_id)
5119 })?;
5120 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5121 as Arc<dyn language::File>);
5122 }
5123
5124 let buffer_id = state.id;
5125 let buffer = cx.add_model(|_| {
5126 Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5127 });
5128 this.incomplete_remote_buffers
5129 .insert(buffer_id, Some(buffer));
5130 }
5131 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5132 let buffer = this
5133 .incomplete_remote_buffers
5134 .get(&chunk.buffer_id)
5135 .cloned()
5136 .flatten()
5137 .ok_or_else(|| {
5138 anyhow!(
5139 "received chunk for buffer {} without initial state",
5140 chunk.buffer_id
5141 )
5142 })?;
5143 let operations = chunk
5144 .operations
5145 .into_iter()
5146 .map(language::proto::deserialize_operation)
5147 .collect::<Result<Vec<_>>>()?;
5148 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5149
5150 if chunk.is_last {
5151 this.incomplete_remote_buffers.remove(&chunk.buffer_id);
5152 this.register_buffer(&buffer, cx)?;
5153 }
5154 }
5155 }
5156
5157 Ok(())
5158 })
5159 }
5160
5161 async fn handle_update_diff_base(
5162 this: ModelHandle<Self>,
5163 envelope: TypedEnvelope<proto::UpdateDiffBase>,
5164 _: Arc<Client>,
5165 mut cx: AsyncAppContext,
5166 ) -> Result<()> {
5167 this.update(&mut cx, |this, cx| {
5168 let buffer_id = envelope.payload.buffer_id;
5169 let diff_base = envelope.payload.diff_base;
5170 if let Some(buffer) = this
5171 .opened_buffers
5172 .get_mut(&buffer_id)
5173 .and_then(|b| b.upgrade(cx))
5174 .or_else(|| {
5175 this.incomplete_remote_buffers
5176 .get(&buffer_id)
5177 .cloned()
5178 .flatten()
5179 })
5180 {
5181 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
5182 }
5183 Ok(())
5184 })
5185 }
5186
5187 async fn handle_update_buffer_file(
5188 this: ModelHandle<Self>,
5189 envelope: TypedEnvelope<proto::UpdateBufferFile>,
5190 _: Arc<Client>,
5191 mut cx: AsyncAppContext,
5192 ) -> Result<()> {
5193 let buffer_id = envelope.payload.buffer_id;
5194
5195 this.update(&mut cx, |this, cx| {
5196 let payload = envelope.payload.clone();
5197 if let Some(buffer) = this
5198 .opened_buffers
5199 .get(&buffer_id)
5200 .and_then(|b| b.upgrade(cx))
5201 .or_else(|| {
5202 this.incomplete_remote_buffers
5203 .get(&buffer_id)
5204 .cloned()
5205 .flatten()
5206 })
5207 {
5208 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5209 let worktree = this
5210 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5211 .ok_or_else(|| anyhow!("no such worktree"))?;
5212 let file = File::from_proto(file, worktree, cx)?;
5213 buffer.update(cx, |buffer, cx| {
5214 buffer.file_updated(Arc::new(file), cx).detach();
5215 });
5216 this.detect_language_for_buffer(&buffer, cx);
5217 }
5218 Ok(())
5219 })
5220 }
5221
5222 async fn handle_save_buffer(
5223 this: ModelHandle<Self>,
5224 envelope: TypedEnvelope<proto::SaveBuffer>,
5225 _: Arc<Client>,
5226 mut cx: AsyncAppContext,
5227 ) -> Result<proto::BufferSaved> {
5228 let buffer_id = envelope.payload.buffer_id;
5229 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5230 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5231 let buffer = this
5232 .opened_buffers
5233 .get(&buffer_id)
5234 .and_then(|buffer| buffer.upgrade(cx))
5235 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5236 anyhow::Ok((project_id, buffer))
5237 })?;
5238 buffer
5239 .update(&mut cx, |buffer, _| {
5240 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
5241 })
5242 .await?;
5243 let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
5244
5245 let (saved_version, fingerprint, mtime) = this
5246 .update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
5247 .await?;
5248 Ok(proto::BufferSaved {
5249 project_id,
5250 buffer_id,
5251 version: serialize_version(&saved_version),
5252 mtime: Some(mtime.into()),
5253 fingerprint: language::proto::serialize_fingerprint(fingerprint),
5254 })
5255 }
5256
5257 async fn handle_reload_buffers(
5258 this: ModelHandle<Self>,
5259 envelope: TypedEnvelope<proto::ReloadBuffers>,
5260 _: Arc<Client>,
5261 mut cx: AsyncAppContext,
5262 ) -> Result<proto::ReloadBuffersResponse> {
5263 let sender_id = envelope.original_sender_id()?;
5264 let reload = this.update(&mut cx, |this, cx| {
5265 let mut buffers = HashSet::default();
5266 for buffer_id in &envelope.payload.buffer_ids {
5267 buffers.insert(
5268 this.opened_buffers
5269 .get(buffer_id)
5270 .and_then(|buffer| buffer.upgrade(cx))
5271 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5272 );
5273 }
5274 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5275 })?;
5276
5277 let project_transaction = reload.await?;
5278 let project_transaction = this.update(&mut cx, |this, cx| {
5279 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5280 });
5281 Ok(proto::ReloadBuffersResponse {
5282 transaction: Some(project_transaction),
5283 })
5284 }
5285
5286 async fn handle_synchronize_buffers(
5287 this: ModelHandle<Self>,
5288 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5289 _: Arc<Client>,
5290 mut cx: AsyncAppContext,
5291 ) -> Result<proto::SynchronizeBuffersResponse> {
5292 let project_id = envelope.payload.project_id;
5293 let mut response = proto::SynchronizeBuffersResponse {
5294 buffers: Default::default(),
5295 };
5296
5297 this.update(&mut cx, |this, cx| {
5298 let Some(guest_id) = envelope.original_sender_id else {
5299 log::error!("missing original_sender_id on SynchronizeBuffers request");
5300 return;
5301 };
5302
5303 this.shared_buffers.entry(guest_id).or_default().clear();
5304 for buffer in envelope.payload.buffers {
5305 let buffer_id = buffer.id;
5306 let remote_version = language::proto::deserialize_version(&buffer.version);
5307 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5308 this.shared_buffers
5309 .entry(guest_id)
5310 .or_default()
5311 .insert(buffer_id);
5312
5313 let buffer = buffer.read(cx);
5314 response.buffers.push(proto::BufferVersion {
5315 id: buffer_id,
5316 version: language::proto::serialize_version(&buffer.version),
5317 });
5318
5319 let operations = buffer.serialize_ops(Some(remote_version), cx);
5320 let client = this.client.clone();
5321 if let Some(file) = buffer.file() {
5322 client
5323 .send(proto::UpdateBufferFile {
5324 project_id,
5325 buffer_id: buffer_id as u64,
5326 file: Some(file.to_proto()),
5327 })
5328 .log_err();
5329 }
5330
5331 client
5332 .send(proto::UpdateDiffBase {
5333 project_id,
5334 buffer_id: buffer_id as u64,
5335 diff_base: buffer.diff_base().map(Into::into),
5336 })
5337 .log_err();
5338
5339 client
5340 .send(proto::BufferReloaded {
5341 project_id,
5342 buffer_id,
5343 version: language::proto::serialize_version(buffer.saved_version()),
5344 mtime: Some(buffer.saved_mtime().into()),
5345 fingerprint: language::proto::serialize_fingerprint(
5346 buffer.saved_version_fingerprint(),
5347 ),
5348 line_ending: language::proto::serialize_line_ending(
5349 buffer.line_ending(),
5350 ) as i32,
5351 })
5352 .log_err();
5353
5354 cx.background()
5355 .spawn(
5356 async move {
5357 let operations = operations.await;
5358 for chunk in split_operations(operations) {
5359 client
5360 .request(proto::UpdateBuffer {
5361 project_id,
5362 buffer_id,
5363 operations: chunk,
5364 })
5365 .await?;
5366 }
5367 anyhow::Ok(())
5368 }
5369 .log_err(),
5370 )
5371 .detach();
5372 }
5373 }
5374 });
5375
5376 Ok(response)
5377 }
5378
5379 async fn handle_format_buffers(
5380 this: ModelHandle<Self>,
5381 envelope: TypedEnvelope<proto::FormatBuffers>,
5382 _: Arc<Client>,
5383 mut cx: AsyncAppContext,
5384 ) -> Result<proto::FormatBuffersResponse> {
5385 let sender_id = envelope.original_sender_id()?;
5386 let format = this.update(&mut cx, |this, cx| {
5387 let mut buffers = HashSet::default();
5388 for buffer_id in &envelope.payload.buffer_ids {
5389 buffers.insert(
5390 this.opened_buffers
5391 .get(buffer_id)
5392 .and_then(|buffer| buffer.upgrade(cx))
5393 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5394 );
5395 }
5396 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5397 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5398 })?;
5399
5400 let project_transaction = format.await?;
5401 let project_transaction = this.update(&mut cx, |this, cx| {
5402 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5403 });
5404 Ok(proto::FormatBuffersResponse {
5405 transaction: Some(project_transaction),
5406 })
5407 }
5408
5409 async fn handle_apply_additional_edits_for_completion(
5410 this: ModelHandle<Self>,
5411 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5412 _: Arc<Client>,
5413 mut cx: AsyncAppContext,
5414 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5415 let (buffer, completion) = this.update(&mut cx, |this, cx| {
5416 let buffer = this
5417 .opened_buffers
5418 .get(&envelope.payload.buffer_id)
5419 .and_then(|buffer| buffer.upgrade(cx))
5420 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5421 let language = buffer.read(cx).language();
5422 let completion = language::proto::deserialize_completion(
5423 envelope
5424 .payload
5425 .completion
5426 .ok_or_else(|| anyhow!("invalid completion"))?,
5427 language.cloned(),
5428 );
5429 Ok::<_, anyhow::Error>((buffer, completion))
5430 })?;
5431
5432 let completion = completion.await?;
5433
5434 let apply_additional_edits = this.update(&mut cx, |this, cx| {
5435 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5436 });
5437
5438 Ok(proto::ApplyCompletionAdditionalEditsResponse {
5439 transaction: apply_additional_edits
5440 .await?
5441 .as_ref()
5442 .map(language::proto::serialize_transaction),
5443 })
5444 }
5445
5446 async fn handle_apply_code_action(
5447 this: ModelHandle<Self>,
5448 envelope: TypedEnvelope<proto::ApplyCodeAction>,
5449 _: Arc<Client>,
5450 mut cx: AsyncAppContext,
5451 ) -> Result<proto::ApplyCodeActionResponse> {
5452 let sender_id = envelope.original_sender_id()?;
5453 let action = language::proto::deserialize_code_action(
5454 envelope
5455 .payload
5456 .action
5457 .ok_or_else(|| anyhow!("invalid action"))?,
5458 )?;
5459 let apply_code_action = this.update(&mut cx, |this, cx| {
5460 let buffer = this
5461 .opened_buffers
5462 .get(&envelope.payload.buffer_id)
5463 .and_then(|buffer| buffer.upgrade(cx))
5464 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5465 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5466 })?;
5467
5468 let project_transaction = apply_code_action.await?;
5469 let project_transaction = this.update(&mut cx, |this, cx| {
5470 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5471 });
5472 Ok(proto::ApplyCodeActionResponse {
5473 transaction: Some(project_transaction),
5474 })
5475 }
5476
5477 async fn handle_lsp_command<T: LspCommand>(
5478 this: ModelHandle<Self>,
5479 envelope: TypedEnvelope<T::ProtoRequest>,
5480 _: Arc<Client>,
5481 mut cx: AsyncAppContext,
5482 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5483 where
5484 <T::LspRequest as lsp::request::Request>::Result: Send,
5485 {
5486 let sender_id = envelope.original_sender_id()?;
5487 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5488 let buffer_handle = this.read_with(&cx, |this, _| {
5489 this.opened_buffers
5490 .get(&buffer_id)
5491 .and_then(|buffer| buffer.upgrade(&cx))
5492 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5493 })?;
5494 let request = T::from_proto(
5495 envelope.payload,
5496 this.clone(),
5497 buffer_handle.clone(),
5498 cx.clone(),
5499 )
5500 .await?;
5501 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5502 let response = this
5503 .update(&mut cx, |this, cx| {
5504 this.request_lsp(buffer_handle, request, cx)
5505 })
5506 .await?;
5507 this.update(&mut cx, |this, cx| {
5508 Ok(T::response_to_proto(
5509 response,
5510 this,
5511 sender_id,
5512 &buffer_version,
5513 cx,
5514 ))
5515 })
5516 }
5517
5518 async fn handle_get_project_symbols(
5519 this: ModelHandle<Self>,
5520 envelope: TypedEnvelope<proto::GetProjectSymbols>,
5521 _: Arc<Client>,
5522 mut cx: AsyncAppContext,
5523 ) -> Result<proto::GetProjectSymbolsResponse> {
5524 let symbols = this
5525 .update(&mut cx, |this, cx| {
5526 this.symbols(&envelope.payload.query, cx)
5527 })
5528 .await?;
5529
5530 Ok(proto::GetProjectSymbolsResponse {
5531 symbols: symbols.iter().map(serialize_symbol).collect(),
5532 })
5533 }
5534
5535 async fn handle_search_project(
5536 this: ModelHandle<Self>,
5537 envelope: TypedEnvelope<proto::SearchProject>,
5538 _: Arc<Client>,
5539 mut cx: AsyncAppContext,
5540 ) -> Result<proto::SearchProjectResponse> {
5541 let peer_id = envelope.original_sender_id()?;
5542 let query = SearchQuery::from_proto(envelope.payload)?;
5543 let result = this
5544 .update(&mut cx, |this, cx| this.search(query, cx))
5545 .await?;
5546
5547 this.update(&mut cx, |this, cx| {
5548 let mut locations = Vec::new();
5549 for (buffer, ranges) in result {
5550 for range in ranges {
5551 let start = serialize_anchor(&range.start);
5552 let end = serialize_anchor(&range.end);
5553 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5554 locations.push(proto::Location {
5555 buffer_id,
5556 start: Some(start),
5557 end: Some(end),
5558 });
5559 }
5560 }
5561 Ok(proto::SearchProjectResponse { locations })
5562 })
5563 }
5564
5565 async fn handle_open_buffer_for_symbol(
5566 this: ModelHandle<Self>,
5567 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5568 _: Arc<Client>,
5569 mut cx: AsyncAppContext,
5570 ) -> Result<proto::OpenBufferForSymbolResponse> {
5571 let peer_id = envelope.original_sender_id()?;
5572 let symbol = envelope
5573 .payload
5574 .symbol
5575 .ok_or_else(|| anyhow!("invalid symbol"))?;
5576 let symbol = this
5577 .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5578 .await?;
5579 let symbol = this.read_with(&cx, |this, _| {
5580 let signature = this.symbol_signature(&symbol.path);
5581 if signature == symbol.signature {
5582 Ok(symbol)
5583 } else {
5584 Err(anyhow!("invalid symbol signature"))
5585 }
5586 })?;
5587 let buffer = this
5588 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5589 .await?;
5590
5591 Ok(proto::OpenBufferForSymbolResponse {
5592 buffer_id: this.update(&mut cx, |this, cx| {
5593 this.create_buffer_for_peer(&buffer, peer_id, cx)
5594 }),
5595 })
5596 }
5597
5598 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5599 let mut hasher = Sha256::new();
5600 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5601 hasher.update(project_path.path.to_string_lossy().as_bytes());
5602 hasher.update(self.nonce.to_be_bytes());
5603 hasher.finalize().as_slice().try_into().unwrap()
5604 }
5605
5606 async fn handle_open_buffer_by_id(
5607 this: ModelHandle<Self>,
5608 envelope: TypedEnvelope<proto::OpenBufferById>,
5609 _: Arc<Client>,
5610 mut cx: AsyncAppContext,
5611 ) -> Result<proto::OpenBufferResponse> {
5612 let peer_id = envelope.original_sender_id()?;
5613 let buffer = this
5614 .update(&mut cx, |this, cx| {
5615 this.open_buffer_by_id(envelope.payload.id, cx)
5616 })
5617 .await?;
5618 this.update(&mut cx, |this, cx| {
5619 Ok(proto::OpenBufferResponse {
5620 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5621 })
5622 })
5623 }
5624
5625 async fn handle_open_buffer_by_path(
5626 this: ModelHandle<Self>,
5627 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5628 _: Arc<Client>,
5629 mut cx: AsyncAppContext,
5630 ) -> Result<proto::OpenBufferResponse> {
5631 let peer_id = envelope.original_sender_id()?;
5632 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5633 let open_buffer = this.update(&mut cx, |this, cx| {
5634 this.open_buffer(
5635 ProjectPath {
5636 worktree_id,
5637 path: PathBuf::from(envelope.payload.path).into(),
5638 },
5639 cx,
5640 )
5641 });
5642
5643 let buffer = open_buffer.await?;
5644 this.update(&mut cx, |this, cx| {
5645 Ok(proto::OpenBufferResponse {
5646 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5647 })
5648 })
5649 }
5650
5651 fn serialize_project_transaction_for_peer(
5652 &mut self,
5653 project_transaction: ProjectTransaction,
5654 peer_id: proto::PeerId,
5655 cx: &mut AppContext,
5656 ) -> proto::ProjectTransaction {
5657 let mut serialized_transaction = proto::ProjectTransaction {
5658 buffer_ids: Default::default(),
5659 transactions: Default::default(),
5660 };
5661 for (buffer, transaction) in project_transaction.0 {
5662 serialized_transaction
5663 .buffer_ids
5664 .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5665 serialized_transaction
5666 .transactions
5667 .push(language::proto::serialize_transaction(&transaction));
5668 }
5669 serialized_transaction
5670 }
5671
5672 fn deserialize_project_transaction(
5673 &mut self,
5674 message: proto::ProjectTransaction,
5675 push_to_history: bool,
5676 cx: &mut ModelContext<Self>,
5677 ) -> Task<Result<ProjectTransaction>> {
5678 cx.spawn(|this, mut cx| async move {
5679 let mut project_transaction = ProjectTransaction::default();
5680 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5681 {
5682 let buffer = this
5683 .update(&mut cx, |this, cx| {
5684 this.wait_for_remote_buffer(buffer_id, cx)
5685 })
5686 .await?;
5687 let transaction = language::proto::deserialize_transaction(transaction)?;
5688 project_transaction.0.insert(buffer, transaction);
5689 }
5690
5691 for (buffer, transaction) in &project_transaction.0 {
5692 buffer
5693 .update(&mut cx, |buffer, _| {
5694 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5695 })
5696 .await?;
5697
5698 if push_to_history {
5699 buffer.update(&mut cx, |buffer, _| {
5700 buffer.push_transaction(transaction.clone(), Instant::now());
5701 });
5702 }
5703 }
5704
5705 Ok(project_transaction)
5706 })
5707 }
5708
5709 fn create_buffer_for_peer(
5710 &mut self,
5711 buffer: &ModelHandle<Buffer>,
5712 peer_id: proto::PeerId,
5713 cx: &mut AppContext,
5714 ) -> u64 {
5715 let buffer_id = buffer.read(cx).remote_id();
5716 if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
5717 updates_tx
5718 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
5719 .ok();
5720 }
5721 buffer_id
5722 }
5723
5724 fn wait_for_remote_buffer(
5725 &mut self,
5726 id: u64,
5727 cx: &mut ModelContext<Self>,
5728 ) -> Task<Result<ModelHandle<Buffer>>> {
5729 let mut opened_buffer_rx = self.opened_buffer.1.clone();
5730
5731 cx.spawn_weak(|this, mut cx| async move {
5732 let buffer = loop {
5733 let Some(this) = this.upgrade(&cx) else {
5734 return Err(anyhow!("project dropped"));
5735 };
5736 let buffer = this.read_with(&cx, |this, cx| {
5737 this.opened_buffers
5738 .get(&id)
5739 .and_then(|buffer| buffer.upgrade(cx))
5740 });
5741 if let Some(buffer) = buffer {
5742 break buffer;
5743 } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5744 return Err(anyhow!("disconnected before buffer {} could be opened", id));
5745 }
5746
5747 this.update(&mut cx, |this, _| {
5748 this.incomplete_remote_buffers.entry(id).or_default();
5749 });
5750 drop(this);
5751 opened_buffer_rx
5752 .next()
5753 .await
5754 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5755 };
5756 buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
5757 Ok(buffer)
5758 })
5759 }
5760
5761 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
5762 let project_id = match self.client_state.as_ref() {
5763 Some(ProjectClientState::Remote {
5764 sharing_has_stopped,
5765 remote_id,
5766 ..
5767 }) => {
5768 if *sharing_has_stopped {
5769 return Task::ready(Err(anyhow!(
5770 "can't synchronize remote buffers on a readonly project"
5771 )));
5772 } else {
5773 *remote_id
5774 }
5775 }
5776 Some(ProjectClientState::Local { .. }) | None => {
5777 return Task::ready(Err(anyhow!(
5778 "can't synchronize remote buffers on a local project"
5779 )))
5780 }
5781 };
5782
5783 let client = self.client.clone();
5784 cx.spawn(|this, cx| async move {
5785 let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
5786 let buffers = this
5787 .opened_buffers
5788 .iter()
5789 .filter_map(|(id, buffer)| {
5790 let buffer = buffer.upgrade(cx)?;
5791 Some(proto::BufferVersion {
5792 id: *id,
5793 version: language::proto::serialize_version(&buffer.read(cx).version),
5794 })
5795 })
5796 .collect();
5797 let incomplete_buffer_ids = this
5798 .incomplete_remote_buffers
5799 .keys()
5800 .copied()
5801 .collect::<Vec<_>>();
5802
5803 (buffers, incomplete_buffer_ids)
5804 });
5805 let response = client
5806 .request(proto::SynchronizeBuffers {
5807 project_id,
5808 buffers,
5809 })
5810 .await?;
5811
5812 let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
5813 let client = client.clone();
5814 let buffer_id = buffer.id;
5815 let remote_version = language::proto::deserialize_version(&buffer.version);
5816 this.read_with(&cx, |this, cx| {
5817 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5818 let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
5819 cx.background().spawn(async move {
5820 let operations = operations.await;
5821 for chunk in split_operations(operations) {
5822 client
5823 .request(proto::UpdateBuffer {
5824 project_id,
5825 buffer_id,
5826 operations: chunk,
5827 })
5828 .await?;
5829 }
5830 anyhow::Ok(())
5831 })
5832 } else {
5833 Task::ready(Ok(()))
5834 }
5835 })
5836 });
5837
5838 // Any incomplete buffers have open requests waiting. Request that the host sends
5839 // creates these buffers for us again to unblock any waiting futures.
5840 for id in incomplete_buffer_ids {
5841 cx.background()
5842 .spawn(client.request(proto::OpenBufferById { project_id, id }))
5843 .detach();
5844 }
5845
5846 futures::future::join_all(send_updates_for_buffers)
5847 .await
5848 .into_iter()
5849 .collect()
5850 })
5851 }
5852
5853 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
5854 self.worktrees(cx)
5855 .map(|worktree| {
5856 let worktree = worktree.read(cx);
5857 proto::WorktreeMetadata {
5858 id: worktree.id().to_proto(),
5859 root_name: worktree.root_name().into(),
5860 visible: worktree.is_visible(),
5861 abs_path: worktree.abs_path().to_string_lossy().into(),
5862 }
5863 })
5864 .collect()
5865 }
5866
5867 fn set_worktrees_from_proto(
5868 &mut self,
5869 worktrees: Vec<proto::WorktreeMetadata>,
5870 cx: &mut ModelContext<Project>,
5871 ) -> Result<()> {
5872 let replica_id = self.replica_id();
5873 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
5874
5875 let mut old_worktrees_by_id = self
5876 .worktrees
5877 .drain(..)
5878 .filter_map(|worktree| {
5879 let worktree = worktree.upgrade(cx)?;
5880 Some((worktree.read(cx).id(), worktree))
5881 })
5882 .collect::<HashMap<_, _>>();
5883
5884 for worktree in worktrees {
5885 if let Some(old_worktree) =
5886 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
5887 {
5888 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
5889 } else {
5890 let worktree =
5891 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
5892 let _ = self.add_worktree(&worktree, cx);
5893 }
5894 }
5895
5896 self.metadata_changed(cx);
5897 for (id, _) in old_worktrees_by_id {
5898 cx.emit(Event::WorktreeRemoved(id));
5899 }
5900
5901 Ok(())
5902 }
5903
5904 fn set_collaborators_from_proto(
5905 &mut self,
5906 messages: Vec<proto::Collaborator>,
5907 cx: &mut ModelContext<Self>,
5908 ) -> Result<()> {
5909 let mut collaborators = HashMap::default();
5910 for message in messages {
5911 let collaborator = Collaborator::from_proto(message)?;
5912 collaborators.insert(collaborator.peer_id, collaborator);
5913 }
5914 for old_peer_id in self.collaborators.keys() {
5915 if !collaborators.contains_key(old_peer_id) {
5916 cx.emit(Event::CollaboratorLeft(*old_peer_id));
5917 }
5918 }
5919 self.collaborators = collaborators;
5920 Ok(())
5921 }
5922
5923 fn deserialize_symbol(
5924 &self,
5925 serialized_symbol: proto::Symbol,
5926 ) -> impl Future<Output = Result<Symbol>> {
5927 let languages = self.languages.clone();
5928 async move {
5929 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5930 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5931 let start = serialized_symbol
5932 .start
5933 .ok_or_else(|| anyhow!("invalid start"))?;
5934 let end = serialized_symbol
5935 .end
5936 .ok_or_else(|| anyhow!("invalid end"))?;
5937 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5938 let path = ProjectPath {
5939 worktree_id,
5940 path: PathBuf::from(serialized_symbol.path).into(),
5941 };
5942 let language = languages
5943 .language_for_file(&path.path, None)
5944 .await
5945 .log_err();
5946 Ok(Symbol {
5947 language_server_name: LanguageServerName(
5948 serialized_symbol.language_server_name.into(),
5949 ),
5950 source_worktree_id,
5951 path,
5952 label: {
5953 match language {
5954 Some(language) => {
5955 language
5956 .label_for_symbol(&serialized_symbol.name, kind)
5957 .await
5958 }
5959 None => None,
5960 }
5961 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
5962 },
5963
5964 name: serialized_symbol.name,
5965 range: Unclipped(PointUtf16::new(start.row, start.column))
5966 ..Unclipped(PointUtf16::new(end.row, end.column)),
5967 kind,
5968 signature: serialized_symbol
5969 .signature
5970 .try_into()
5971 .map_err(|_| anyhow!("invalid signature"))?,
5972 })
5973 }
5974 }
5975
5976 async fn handle_buffer_saved(
5977 this: ModelHandle<Self>,
5978 envelope: TypedEnvelope<proto::BufferSaved>,
5979 _: Arc<Client>,
5980 mut cx: AsyncAppContext,
5981 ) -> Result<()> {
5982 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
5983 let version = deserialize_version(&envelope.payload.version);
5984 let mtime = envelope
5985 .payload
5986 .mtime
5987 .ok_or_else(|| anyhow!("missing mtime"))?
5988 .into();
5989
5990 this.update(&mut cx, |this, cx| {
5991 let buffer = this
5992 .opened_buffers
5993 .get(&envelope.payload.buffer_id)
5994 .and_then(|buffer| buffer.upgrade(cx))
5995 .or_else(|| {
5996 this.incomplete_remote_buffers
5997 .get(&envelope.payload.buffer_id)
5998 .and_then(|b| b.clone())
5999 });
6000 if let Some(buffer) = buffer {
6001 buffer.update(cx, |buffer, cx| {
6002 buffer.did_save(version, fingerprint, mtime, cx);
6003 });
6004 }
6005 Ok(())
6006 })
6007 }
6008
6009 async fn handle_buffer_reloaded(
6010 this: ModelHandle<Self>,
6011 envelope: TypedEnvelope<proto::BufferReloaded>,
6012 _: Arc<Client>,
6013 mut cx: AsyncAppContext,
6014 ) -> Result<()> {
6015 let payload = envelope.payload;
6016 let version = deserialize_version(&payload.version);
6017 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
6018 let line_ending = deserialize_line_ending(
6019 proto::LineEnding::from_i32(payload.line_ending)
6020 .ok_or_else(|| anyhow!("missing line ending"))?,
6021 );
6022 let mtime = payload
6023 .mtime
6024 .ok_or_else(|| anyhow!("missing mtime"))?
6025 .into();
6026 this.update(&mut cx, |this, cx| {
6027 let buffer = this
6028 .opened_buffers
6029 .get(&payload.buffer_id)
6030 .and_then(|buffer| buffer.upgrade(cx))
6031 .or_else(|| {
6032 this.incomplete_remote_buffers
6033 .get(&payload.buffer_id)
6034 .cloned()
6035 .flatten()
6036 });
6037 if let Some(buffer) = buffer {
6038 buffer.update(cx, |buffer, cx| {
6039 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
6040 });
6041 }
6042 Ok(())
6043 })
6044 }
6045
6046 #[allow(clippy::type_complexity)]
6047 fn edits_from_lsp(
6048 &mut self,
6049 buffer: &ModelHandle<Buffer>,
6050 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
6051 version: Option<i32>,
6052 cx: &mut ModelContext<Self>,
6053 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
6054 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
6055 cx.background().spawn(async move {
6056 let snapshot = snapshot?;
6057 let mut lsp_edits = lsp_edits
6058 .into_iter()
6059 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
6060 .collect::<Vec<_>>();
6061 lsp_edits.sort_by_key(|(range, _)| range.start);
6062
6063 let mut lsp_edits = lsp_edits.into_iter().peekable();
6064 let mut edits = Vec::new();
6065 while let Some((range, mut new_text)) = lsp_edits.next() {
6066 // Clip invalid ranges provided by the language server.
6067 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
6068 ..snapshot.clip_point_utf16(range.end, Bias::Left);
6069
6070 // Combine any LSP edits that are adjacent.
6071 //
6072 // Also, combine LSP edits that are separated from each other by only
6073 // a newline. This is important because for some code actions,
6074 // Rust-analyzer rewrites the entire buffer via a series of edits that
6075 // are separated by unchanged newline characters.
6076 //
6077 // In order for the diffing logic below to work properly, any edits that
6078 // cancel each other out must be combined into one.
6079 while let Some((next_range, next_text)) = lsp_edits.peek() {
6080 if next_range.start.0 > range.end {
6081 if next_range.start.0.row > range.end.row + 1
6082 || next_range.start.0.column > 0
6083 || snapshot.clip_point_utf16(
6084 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
6085 Bias::Left,
6086 ) > range.end
6087 {
6088 break;
6089 }
6090 new_text.push('\n');
6091 }
6092 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
6093 new_text.push_str(next_text);
6094 lsp_edits.next();
6095 }
6096
6097 // For multiline edits, perform a diff of the old and new text so that
6098 // we can identify the changes more precisely, preserving the locations
6099 // of any anchors positioned in the unchanged regions.
6100 if range.end.row > range.start.row {
6101 let mut offset = range.start.to_offset(&snapshot);
6102 let old_text = snapshot.text_for_range(range).collect::<String>();
6103
6104 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
6105 let mut moved_since_edit = true;
6106 for change in diff.iter_all_changes() {
6107 let tag = change.tag();
6108 let value = change.value();
6109 match tag {
6110 ChangeTag::Equal => {
6111 offset += value.len();
6112 moved_since_edit = true;
6113 }
6114 ChangeTag::Delete => {
6115 let start = snapshot.anchor_after(offset);
6116 let end = snapshot.anchor_before(offset + value.len());
6117 if moved_since_edit {
6118 edits.push((start..end, String::new()));
6119 } else {
6120 edits.last_mut().unwrap().0.end = end;
6121 }
6122 offset += value.len();
6123 moved_since_edit = false;
6124 }
6125 ChangeTag::Insert => {
6126 if moved_since_edit {
6127 let anchor = snapshot.anchor_after(offset);
6128 edits.push((anchor..anchor, value.to_string()));
6129 } else {
6130 edits.last_mut().unwrap().1.push_str(value);
6131 }
6132 moved_since_edit = false;
6133 }
6134 }
6135 }
6136 } else if range.end == range.start {
6137 let anchor = snapshot.anchor_after(range.start);
6138 edits.push((anchor..anchor, new_text));
6139 } else {
6140 let edit_start = snapshot.anchor_after(range.start);
6141 let edit_end = snapshot.anchor_before(range.end);
6142 edits.push((edit_start..edit_end, new_text));
6143 }
6144 }
6145
6146 Ok(edits)
6147 })
6148 }
6149
6150 fn buffer_snapshot_for_lsp_version(
6151 &mut self,
6152 buffer: &ModelHandle<Buffer>,
6153 version: Option<i32>,
6154 cx: &AppContext,
6155 ) -> Result<TextBufferSnapshot> {
6156 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
6157
6158 if let Some(version) = version {
6159 let buffer_id = buffer.read(cx).remote_id();
6160 let snapshots = self
6161 .buffer_snapshots
6162 .get_mut(&buffer_id)
6163 .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
6164 let found_snapshot = snapshots
6165 .binary_search_by_key(&version, |e| e.0)
6166 .map(|ix| snapshots[ix].1.clone())
6167 .map_err(|_| {
6168 anyhow!(
6169 "snapshot not found for buffer {} at version {}",
6170 buffer_id,
6171 version
6172 )
6173 })?;
6174 snapshots.retain(|(snapshot_version, _)| {
6175 snapshot_version + OLD_VERSIONS_TO_RETAIN >= version
6176 });
6177 Ok(found_snapshot)
6178 } else {
6179 Ok((buffer.read(cx)).text_snapshot())
6180 }
6181 }
6182
6183 fn language_server_for_buffer(
6184 &self,
6185 buffer: &Buffer,
6186 cx: &AppContext,
6187 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6188 let server_id = self.language_server_id_for_buffer(buffer, cx)?;
6189 let server = self.language_servers.get(&server_id)?;
6190 if let LanguageServerState::Running {
6191 adapter, server, ..
6192 } = server
6193 {
6194 Some((adapter, server))
6195 } else {
6196 None
6197 }
6198 }
6199
6200 fn language_server_id_for_buffer(&self, buffer: &Buffer, cx: &AppContext) -> Option<usize> {
6201 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6202 let name = language.lsp_adapter()?.name.clone();
6203 let worktree_id = file.worktree_id(cx);
6204 let key = (worktree_id, name);
6205 self.language_server_ids.get(&key).copied()
6206 } else {
6207 None
6208 }
6209 }
6210}
6211
6212impl WorktreeHandle {
6213 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6214 match self {
6215 WorktreeHandle::Strong(handle) => Some(handle.clone()),
6216 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6217 }
6218 }
6219}
6220
6221impl OpenBuffer {
6222 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
6223 match self {
6224 OpenBuffer::Strong(handle) => Some(handle.clone()),
6225 OpenBuffer::Weak(handle) => handle.upgrade(cx),
6226 OpenBuffer::Operations(_) => None,
6227 }
6228 }
6229}
6230
6231pub struct PathMatchCandidateSet {
6232 pub snapshot: Snapshot,
6233 pub include_ignored: bool,
6234 pub include_root_name: bool,
6235}
6236
6237impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6238 type Candidates = PathMatchCandidateSetIter<'a>;
6239
6240 fn id(&self) -> usize {
6241 self.snapshot.id().to_usize()
6242 }
6243
6244 fn len(&self) -> usize {
6245 if self.include_ignored {
6246 self.snapshot.file_count()
6247 } else {
6248 self.snapshot.visible_file_count()
6249 }
6250 }
6251
6252 fn prefix(&self) -> Arc<str> {
6253 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6254 self.snapshot.root_name().into()
6255 } else if self.include_root_name {
6256 format!("{}/", self.snapshot.root_name()).into()
6257 } else {
6258 "".into()
6259 }
6260 }
6261
6262 fn candidates(&'a self, start: usize) -> Self::Candidates {
6263 PathMatchCandidateSetIter {
6264 traversal: self.snapshot.files(self.include_ignored, start),
6265 }
6266 }
6267}
6268
6269pub struct PathMatchCandidateSetIter<'a> {
6270 traversal: Traversal<'a>,
6271}
6272
6273impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6274 type Item = fuzzy::PathMatchCandidate<'a>;
6275
6276 fn next(&mut self) -> Option<Self::Item> {
6277 self.traversal.next().map(|entry| {
6278 if let EntryKind::File(char_bag) = entry.kind {
6279 fuzzy::PathMatchCandidate {
6280 path: &entry.path,
6281 char_bag,
6282 }
6283 } else {
6284 unreachable!()
6285 }
6286 })
6287 }
6288}
6289
6290impl Entity for Project {
6291 type Event = Event;
6292
6293 fn release(&mut self, cx: &mut gpui::AppContext) {
6294 match &self.client_state {
6295 Some(ProjectClientState::Local { .. }) => {
6296 let _ = self.unshare_internal(cx);
6297 }
6298 Some(ProjectClientState::Remote { remote_id, .. }) => {
6299 let _ = self.client.send(proto::LeaveProject {
6300 project_id: *remote_id,
6301 });
6302 self.disconnected_from_host_internal(cx);
6303 }
6304 _ => {}
6305 }
6306 }
6307
6308 fn app_will_quit(
6309 &mut self,
6310 _: &mut AppContext,
6311 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6312 let shutdown_futures = self
6313 .language_servers
6314 .drain()
6315 .map(|(_, server_state)| async {
6316 match server_state {
6317 LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6318 LanguageServerState::Starting(starting_server) => {
6319 starting_server.await?.shutdown()?.await
6320 }
6321 }
6322 })
6323 .collect::<Vec<_>>();
6324
6325 Some(
6326 async move {
6327 futures::future::join_all(shutdown_futures).await;
6328 }
6329 .boxed(),
6330 )
6331 }
6332}
6333
6334impl Collaborator {
6335 fn from_proto(message: proto::Collaborator) -> Result<Self> {
6336 Ok(Self {
6337 peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
6338 replica_id: message.replica_id as ReplicaId,
6339 })
6340 }
6341}
6342
6343impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6344 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6345 Self {
6346 worktree_id,
6347 path: path.as_ref().into(),
6348 }
6349 }
6350}
6351
6352fn split_operations(
6353 mut operations: Vec<proto::Operation>,
6354) -> impl Iterator<Item = Vec<proto::Operation>> {
6355 #[cfg(any(test, feature = "test-support"))]
6356 const CHUNK_SIZE: usize = 5;
6357
6358 #[cfg(not(any(test, feature = "test-support")))]
6359 const CHUNK_SIZE: usize = 100;
6360
6361 let mut done = false;
6362 std::iter::from_fn(move || {
6363 if done {
6364 return None;
6365 }
6366
6367 let operations = operations
6368 .drain(..cmp::min(CHUNK_SIZE, operations.len()))
6369 .collect::<Vec<_>>();
6370 if operations.is_empty() {
6371 done = true;
6372 }
6373 Some(operations)
6374 })
6375}
6376
6377fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6378 proto::Symbol {
6379 language_server_name: symbol.language_server_name.0.to_string(),
6380 source_worktree_id: symbol.source_worktree_id.to_proto(),
6381 worktree_id: symbol.path.worktree_id.to_proto(),
6382 path: symbol.path.path.to_string_lossy().to_string(),
6383 name: symbol.name.clone(),
6384 kind: unsafe { mem::transmute(symbol.kind) },
6385 start: Some(proto::PointUtf16 {
6386 row: symbol.range.start.0.row,
6387 column: symbol.range.start.0.column,
6388 }),
6389 end: Some(proto::PointUtf16 {
6390 row: symbol.range.end.0.row,
6391 column: symbol.range.end.0.column,
6392 }),
6393 signature: symbol.signature.to_vec(),
6394 }
6395}
6396
6397fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6398 let mut path_components = path.components();
6399 let mut base_components = base.components();
6400 let mut components: Vec<Component> = Vec::new();
6401 loop {
6402 match (path_components.next(), base_components.next()) {
6403 (None, None) => break,
6404 (Some(a), None) => {
6405 components.push(a);
6406 components.extend(path_components.by_ref());
6407 break;
6408 }
6409 (None, _) => components.push(Component::ParentDir),
6410 (Some(a), Some(b)) if components.is_empty() && a == b => (),
6411 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6412 (Some(a), Some(_)) => {
6413 components.push(Component::ParentDir);
6414 for _ in base_components {
6415 components.push(Component::ParentDir);
6416 }
6417 components.push(a);
6418 components.extend(path_components.by_ref());
6419 break;
6420 }
6421 }
6422 }
6423 components.iter().map(|c| c.as_os_str()).collect()
6424}
6425
6426impl Item for Buffer {
6427 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6428 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6429 }
6430
6431 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
6432 File::from_dyn(self.file()).map(|file| ProjectPath {
6433 worktree_id: file.worktree_id(cx),
6434 path: file.path().clone(),
6435 })
6436 }
6437}