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